【问题标题】:python script for inserting batch data into mysql table用于将批处理数据插入mysql表的python脚本
【发布时间】:2014-09-08 16:12:22
【问题描述】:

我正在编写一个用于将 csv 文件插入 mysql 表的 python 脚本。我遇到的问题是它只插入一行并在此之后终止。

#!/usr/bin/python

import sys
import csv 
import MySQLdb

db = MySQLdb.connect(host="localhost",user="root",passwd="password",db="AM")
cur = db.cursor()


f = open(sys.argv[1],'rt')
try:
    reader = csv.reader(f)
    headers = next(reader)
    for row in reader:
        col1 = row[0]
        col2 = row[1]
        col3 = row[2]
        col4 = row[3]
        col5 = row[4]
        col6 = row[5]
except:
     print sys.exc_info()


sql = "Insert ignore into my_table(col1, col2, col3, col4, col5, col6) values ('%s', '%s', '%s', '%s', '%s', '%s');" % (col1, col2, col3, col4, col5, col6)
try:
    cur.execute(sql)
    db.commit()
except:
    db.rollback()
finally:
    db.close() 

【问题讨论】:

    标签: python mysql mysql-python


    【解决方案1】:
    sql = "Insert ignore into table(a,b,c,d,e,f) values ('%s', '%s', '%c', '%s', '%s', '%s');" % (list1, list2, list3, list4, list5, list6)
    

    您的表实际上命名为“table”吗?如果是这样,您应该用双引号将其括起来,如下所示:

    sql = "Insert ignore into \"table\"(a,b,c,d,e,f) values ('%s', '%s', '%c', '%s', '%s', '%s');" % (list1, list2, list3, list4, list5, list6)
    

    table 是一个 SQL 关键字。

    【讨论】:

    • 问题似乎出在我的字符串格式上。用双引号括住我的表名会在值处产生另一个语法错误。
    • 尝试在 \"table\" 之后添加空格,即 \"table\" (a,b,c,d,e,f)。您的列实际上命名为 a、b、c、d、e、f 吗?
    • 原来问题是因为我忘了添加except。现在我遇到了一个不同的问题。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-25
    • 2017-04-01
    相关资源
    最近更新 更多