python-mysql:設定資料類型初探

來源:互聯網
上載者:User

標籤:into   arch   pymysql   內建   open   arm   das   cursor   zhang   

  pyton3.6,pymysql

  pandas.read_csv讀取的資料,儲存到資料庫中。發現data = data.astype(float),data的資料類型還是numpy.float64。

  python的資料類型,如str、Int、float等,跟寫入mysql時的資料類型沒有半毛錢關係。

  它們是這樣傳遞的:python的資料類型-->insert語句,轉化為字串-->轉換為mysql欄位的資料類型。

  例如:sql = "insert into tb_name values(‘s%‘, ‘%d‘,‘%0.2f‘)" % (‘Mary‘, 24, 12000.00),傳入的資料類型不相同,但是都要在裡面加上單引號轉為字串,再導進mysql中。

 1 import pymysql 2 import pandas as pd 3  4 dbcon = pymysql.connect(host=‘localhost‘, 5                         port=3306, 6                         user=‘root‘, 7                         passwd=‘1234‘, 8                         db=‘model_database‘ 9                         )10 cursor = dbcon.cursor()11 data = pd.read_csv(r‘C:\Users\zhangjingyu\PycharmProjects\MyModels\knnCluster\data.csv‘)12 13 sql1 = ‘DROP TABLE IF EXISTS cluster_data‘14 cursor.execute(sql1)15 sql2 = ‘CREATE TABLE cluster_data(x FLOAT (8,6),y VARCHAR (20))‘16 cursor.execute(sql2)17 18 data_mysql = []19 20 data_mysql = [(float(data.iloc[i, 0]), float(data.iloc[i, 1])) for i in range(data.shape[0])]21 cursor.executemany(‘INSERT INTO cluster_data VALUES(%s,%s)‘, data_mysql)22 try:23     dbcon.commit()24     print(‘success written!‘)25 except:26     dbcon.rollback()27     print(‘failed written!‘)28 finally:29     cursor.close()30     dbcon.close()
View Code

  結果如下:

  

  實在有必要執行其它操作,倒建議直接在SQL命令裡寫,內建SQL語句的補全功能。

python-mysql:設定資料類型初探

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.