Using Python variables in MySQL insert statement

微笑、不失礼 提交于 2021-02-08 11:14:03

问题


I've been trying for a while now and have look online and can't figure it out.

Variables are numbers and animals

sql = ("INSERT INTO favourite (number, info) VALUES (numbers, animals  )")
cursor.execute(*sql)
conn.comit()

回答1:


Use:

sql=("INSERT INTO favourite (number, info) VALUES ({},{})".format(numbers,animals))

Its always good to use format as per future references. Check https://docs.python.org/release/3.1.5/library/stdtypes.html#old-string-formatting-operations




回答2:


sql = ("INSERT INTO favourite (number, info) VALUES (%s, %s)", (numbers, animals))

for safety, always use escape, see http://dev.mysql.com/doc/refman/5.7/en/string-literals.html




回答3:


I think the following should work. Let me know how it works out for you.

sql=("INSERT INTO favourite (number, info) VALUES ({},{})".format(numbers,animals))



来源:https://stackoverflow.com/questions/37405287/using-python-variables-in-mysql-insert-statement

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