Python:将带有blob的csv文件导入Mysql表

时间:2018-06-12 00:43:34

标签: python mysql csv byte blob

我将包含blob观察的Mysql表导出到csv文件中,但是当我尝试将csv文件加载到另一个Mysql表中时,我得到了:"数据太长了以及列' IMAGE&#39 ;在第1行和第34行; PS:Longblob不起作用

这是代码(thx求助)

import mysql.connector
import csv



try:
    connection=mysql.connector.connect(user='root', password ='12345', database='sakila')
    cursor=connection.cursor()
    sql=("select picture from staff")
    cursor.execute(sql)
    result=cursor.fetchall()
    variables = cursor.column_names

    with open("MySQL-connector_csv.csv", "w", newline='\n', encoding='UTF-8') as c:
            writer = csv.writer(c)
            writer.writerow(variables)
            for data in result:
                writer.writerow(data)
    connection.commit()


    sql=("CREATE TABLE IF NOT EXISTS test (ID INTEGER AUTO_INCREMENT,IMAGE BLOB,PRIMARY KEY (ID));")
    cursor.execute(sql)
    connection.commit()

    with open("MySQL-connector_csv.csv", "r", encoding="UTF-8") as file:
        csv_data = csv.reader(file, delimiter =',')
        next(csv_data, None) #skip the variable names
        for row in csv_data:
            sql = "INSERT INTO `test` (`IMAGE`) VALUES (%s)"
            cursor.execute(sql, row)
    connection.commit()


finally:
    connection.close()

0 个答案:

没有答案