我有一张表格,我需要从txt
文件,日期和来源python
变量中填充电子邮件地址。在代码中,a
是来自txt
和b
的变量,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'
非常感谢任何帮助
答案 0 :(得分:4)
替换查询字符串
query = (" INSERT INTO test(a,b,c) VALUES %s") %(row,)
或
query = (" INSERT INTO test(a,b,c) VALUES %s") % str(row)
希望它对你有用......