简体   繁体   中英

Insert a value in a Mysql database using Python

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:

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.

Use cursor.execute to bind Value into your query.

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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