2

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.

Asdalud
  • 149
  • 9
  • 1
    Possible duplicate of [How to use variables in SQL statement in Python?](https://stackoverflow.com/questions/902408/how-to-use-variables-in-sql-statement-in-python) – Ilja Everilä Jun 05 '18 at 09:25

2 Answers2

1

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.

Brad Koch
  • 19,267
  • 19
  • 110
  • 137
-2

Use string formatting to provide the Value variable

cursor.execute("""INSERT INTO test VALUES ('Number', %s)""" % Value)
ODiogoSilva
  • 2,394
  • 1
  • 19
  • 20