简体   繁体   中英

How to create table and import data in mysql with python

I want to create a table in MYSQL with python and then import data from csv to that. my code to create the table is:

    sqlcmd="CREATE TABLE IF NOT EXISTS PA_TEST_CREDITS(`Identifier` TINYTEXT,`Test_Name` TINYTEXT,`Test_Component_Code` TINYTEXT,`Test_Component` TINYTEXT,`Test_Score` TINYINT,`Course_Prefix` TINYTEXT,`Course_Number` TINYTEXT,`Course_Title` TINYTEXT,`EARN_CREDIT` TINYTEXT,`Earned_Credit_Flag` TINYINT)"
cursor.execute(sqlcmd)
rconn.commit()

This code creates my table. for importing data I have used this code:

import csv
with open('PA_TEST_CREDITS.csv') as csvfile:
    csv_data=csv.reader(csvfile)
    for row in csv_data:
        cursor.execute("INSERT INTO PA_TEST_CREDITS(Identifier, Test Name, Test Component Code, Test Component, Test Score, Course Prefix, Course Number, Course Title,EARN_CREDIT,Earned Credit Flag) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", row)

The error is "Data truncated for column 'Test_score' at row 1".

It would be appreciated if you help me. Thanks

Try row.split(“,”) as the second parameter for your execute command, so you pass an array instead of a string, since it might be trying to use the same string for all your parameters, and when it reaches the first non-text column it fails.

Also consider that Tinyint is only able to hold values from -128 to 127 (if signed) or from 0 to 255 (if unsigned).

If you have greater values on that CSV for the column it is also going to get truncated.

If so, check out the right integer type you need according to the values you're going to be using here: https://dev.mysql.com/doc/refman/5.7/en/integer-types.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM