使用带有外部变量的python将数据插入到mysql中

时间:2015-05-25 09:01:52

标签: python mysql csv

我有一张表格,我需要从txt文件,日期和来源python变量中填充电子邮件地址。在代码中,a是来自txtb的变量,c是我需要插入的python变量

import csv,MySQLdb,os,os.path,datetime as dt
from sys import argv
path = argv
prompt = '>'
filename = raw_input(prompt)
fname = os.path.basename(filename)
source = fname
print "",source
date = dt.datetime.today().strftime("%d/%m/%y")
date_log = date
print "",date_log
db = MySQLdb.connect("localhost","root","passwd","testdb")
x = db.cursor()
csv_data  = csv.reader(file(filename))
for row in csv_data:
    print row
    query = (" INSERT INTO test(a,b,c) VALUES (%s,%s,%s)",row)
    x.execute(query, (date_log, source))
db.commit()
db.close()

以下是一些错误:

File "csv2mysql.py", line 31, in <module>
    x.execute(query, (date_log, source))
  File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py",line159,in execute
    query = query % db.literal(args)
TypeError: unsupported operand type(s) for %: 'tuple' and 'tuple'

非常感谢任何帮助

1 个答案:

答案 0 :(得分:4)

替换查询字符串

 query = (" INSERT INTO test(a,b,c) VALUES %s") %(row,)

 query = (" INSERT INTO test(a,b,c) VALUES %s") % str(row)

希望它对你有用......