Python-mysql: A preliminary study of setting data types

Source: Internet
Author: User

Pyton3.6,pymysql

Pandas.read_csv the data to be read and saved to the database. data = Data.astype (float) is found, and it is numpy.float64.

Python's data types, such as STR, Int, float, etc., do not have a half-penny relationship with the data type when it is written to MySQL.

They are passed in this way: Python's data type-->insert statement, converted to a string--and converted to a MySQL field data type.

For example: sql = "INSERT into tb_name values (' s% ', '%d ', '%0.2f ')"% (' Mary ', 24, 12000.00), the incoming data type is not the same, but all the inside with a single quote to the string, into MySQL again.

1 Import Pymysql2Import Pandas asPD3 4Dbcon = Pymysql.connect (host='localhost',5port=3306,6User='Root',7Passwd='1234',8db='Model_database'9                         )Tencursor =dbcon.cursor () Onedata = Pd.read_csv (r'C:\Users\zhangjingyu\PycharmProjects\MyModels\knnCluster\data.csv') A  -SQL1 ='DROP TABLE IF EXISTS cluster_data' - Cursor.execute (SQL1) theSQL2 ='CREATE TABLE cluster_data (x FLOAT (8,6), y VARCHAR ())' - Cursor.execute (SQL2) -  -Data_mysql = [] +  -Data_mysql = [(float(Data.iloc[i,0]),float(Data.iloc[i,1])) forIinchRange (data.shape[0])] +Cursor.executemany ('INSERT into Cluster_data VALUES (%s,%s)', Data_mysql) A Try: at Dbcon.commit () -Print'Success written!') - except: - Dbcon.rollback () -Print'failed written!') - finally: in cursor.close () -Dbcon.close ()
View Code

The results are as follows:

  

It is necessary to perform other operations, which are suggested to be written directly in the SQL command, with the complement function of the SQL statement.

Python-mysql: A preliminary study of setting data types

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.