使用Python在Mysql数据库中插入一个值

时间:2022-10-13 12:02:52

I am trying to insert values typed from me to a MySQL database. I am using python 3.4 and mysql.connector. Here is the part of the script:

我试图将从我输入的值插入MySQL数据库。我使用的是python 3.4和mysql.connector。这是脚本的一部分:

Value = int(input("Type a number between 1 and 10: "))
cursor.execute("""INSERT INTO test VALUES ('Number', Value )""")

I am actually trying to find out how to get what i am inserting from my keyboard into the second field of the test table. As it is right now it gives me a SQL syntax error. Please help. Thanks in advance.

我实际上试图找出如何从我的键盘插入测试表的第二个字段。因为它现在它给我一个SQL语法错误。请帮忙。提前致谢。

2 个解决方案

#1


Use cursor.execute to bind Value into your query.

使用cursor.execute将Value绑定到查询中。

cursor.execute("INSERT INTO test VALUES ('Number', %s)", (Value,)) 

This is preferable over the other answers because it protects against SQL injection.

这比其他答案更可取,因为它可以防止SQL注入。

#2


Use string formatting to provide the Value variable

使用字符串格式提供Value变量

cursor.execute("""INSERT INTO test VALUES ('Number', %s)""" % Value)

#1


Use cursor.execute to bind Value into your query.

使用cursor.execute将Value绑定到查询中。

cursor.execute("INSERT INTO test VALUES ('Number', %s)", (Value,)) 

This is preferable over the other answers because it protects against SQL injection.

这比其他答案更可取,因为它可以防止SQL注入。

#2


Use string formatting to provide the Value variable

使用字符串格式提供Value变量

cursor.execute("""INSERT INTO test VALUES ('Number', %s)""" % Value)