python MySQLDb插入准备好的语句

时间:2013-08-08 14:37:22

标签: python mysql database mysql-python

我有一个包含字段的表

TABLE_PASTE(
      user_text longtext NOT NULL,
      number integer NOT NULL
 )

我正在尝试使用MySQLDb驱动程序从python中在此表TABLE_PASTE中插入一行。

text="large_text"
value = 1
cursor.execute("Update TABLE_PASTE set user_text = ? where number = ?",(text,value))

收到此错误

query = query % db.literal(args)
TypeError: not all arguments converted during string formatting

2 个答案:

答案 0 :(得分:9)

使用MySQLdb,您希望在Python 2.x中使用类似于字符串格式的参数化(在技术上不存在于python中的预处理语句)语句。

cursor.execute("Update TABLE_PASTE set user_text = %s where number = %s",(text,value))

请注意,即使您的valueint,您仍然必须使用%s在查询中对其进行格式化。

您可以在MySQLdb here上找到一个很好的教程。

答案 1 :(得分:-7)

只需使用

即可
cursor.execute("Update TABLE_PASTE set user_text = {} where number = {}" .format(text,value))

其中format函数将相应地格式化您的输入,无论是int还是字符串!