python MySQLDb insert with prepared Statements [duplicate]

走远了吗. 提交于 2020-01-04 13:13:28

问题


I have a table with fields

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

I am trying to insert a row in this table TABLE_PASTE from python using MySQLDb driver.

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

Am getting this error

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

回答1:


With MySQLdb you want to use parameterized (prepared statements technically don't exist in python) statements similar to string formatting in Python 2.x.

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

Note that even though your value is an int you still must use %s to format it in your query.

You can find a good tutorial on MySQLdb here.




回答2:


simply you can just use

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

where format function will format your input accordingly whether its an int or a string!



来源:https://stackoverflow.com/questions/18128870/python-mysqldb-insert-with-prepared-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!