以下代码
varlist =[]
for key, value in json_obj.iteritems():
print key, value
varlist = varlist + ["string"]
print varlist
params = ['?' for item in varlist]
query_string = 'INSERT INTO test_table VALUES (%s);' % ','.join(params)
print query_string
cursor.execute(query_string, varlist)
产生以下
['string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string']
INSERT INTO test_table VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);
Traceback (most recent call last):
File "./vpn.py", line 26, in <module>
cursor.execute(query_string, varlist)
File "/usr/local/lib/python2.7/dist-packages/pymysql/cursors.py", line 164, in execute
query = self.mogrify(query, args)
File "/usr/local/lib/python2.7/dist-packages/pymysql/cursors.py", line 143, in mogrify
query = query % self._escape_args(args, conn)
TypeError: not all arguments converted during string formatting
我也试过
cursor.execute(query_string, (varlist,))
但它也不起作用。任何想法是什么问题?
答案 0 :(得分:0)
来自documentation中的示例:
insert_stmt = (
"INSERT INTO employees (emp_no, first_name, last_name, hire_date) "
"VALUES (%s, %s, %s, %s)"
)
data = (2, 'Jane', 'Doe', datetime.date(2012, 3, 23))
cursor.execute(insert_stmt, data)
在查询行中注意%s
。这就是cursor.execute
知道放置值的位置的方式。在您的情况下,查询已经填写并导致错误。