我对MySQLdb有一个问题,以前没有任何问题可以帮助我。我在python中有一个名为alltitles的列表,我想将它插入到MySQL的表中。我在python中有以下代码:
for s in range(0,len(alltitles)):
print alltitles[s]
query = "INSERT INTO table (colname) VALUES ("+alltitles[s]+")"
x=conn.cursor()
x.execute(query, alltitles[s])
row = x.fetchall()
它返回此错误:
Traceback (most recent call last):
File "<pyshell#180>", line 5, in <module>
x.execute(query, alltitles[s])
File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 159, in execute
query = query % db.literal(args)
TypeError: not all arguments converted during string formatting
感谢任何建议,谢谢。
答案 0 :(得分:0)
您将值作为文字放在字符串中,并作为查询的参数。你应该只在一个地方做,那应该作为参数。
(另请注意,在Python中,您不应该使用索引遍历范围;迭代该事物本身。)
x = conn.cursor()
for title in alltitles:
print title
query = "INSERT INTO table (colname) VALUES (%s)"
x.execute(query, title)
row = x.fetchall()
答案 1 :(得分:0)
另外,尝试使用:
for title_index,title in enumerate(alltitles):
print title_index, title
...
(alltitles [title_index]也会给你标题)