简体   繁体   English

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

[英]Insert a value in a Mysql database using Python

I am trying to insert values typed from me to a MySQL database. 我试图将我输入的值插入MySQL数据库。 I am using python 3.4 and mysql.connector. 我正在使用python 3.4和mysql.connector。 Here is the part of the script: 这是脚本的一部分:

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. 现在,它给了我一个SQL语法错误。 Please help. 请帮忙。 Thanks in advance. 提前致谢。

Use cursor.execute to bind Value into your query. 使用cursor.executeValue绑定到查询中。

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

This is preferable over the other answers because it protects against SQL injection. 这比其他答案更好,因为它可以防止SQL注入。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM