How to give input to MySql connector through Python

Question:

By using mysql-connector-python package

mycursor = mydb.cursor()
new_pin = int(input("Enter Pin Number:"))
Pins_Entry = "INSERT INTO ATM_DEMO_PINS(PIN) VALUES(%s)"  # Middle Program 1
mycursor.execute(Pins_Entry, new_pin)
mydb.commit()

Showing Error:

mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s)' at line 3
Asked By: Anand D

||

Answers:

This seems to be a perennial error here on SO, but you need to obtain a cursor with the prepared statement mode turned on:

mycursor = mydb.cursor(prepared=True)     # change is HERE
new_pin = int(input("Enter Pin Number:"))
Pins_Entry = "INSERT INTO ATM_DEMO_PINS(PIN) VALUES(%s)"  # Middle Program 1
mycursor.execute(Pins_Entry, (new_pin,))
mydb.commit()

The error you are seeing would be consistent with MySQL parsing the query with %s being a literal part of the query, rather than a placeholder.

Answered By: Tim Biegeleisen

Your problem is in this line

mycursor.execute(Pins_Entry, new_pin)

It will be like this

mycursor.execute(Pins_Entry%new_pin)
Answered By: Ujjwal Dash

mycursor = mydb.cursor()
new_pin = int(input("Enter Pin Number:"))
Pins_Entry = "INSERT INTO ATM_DEMO_PINS(PIN) VALUES(%s)"  # Middle Program 1
mycursor.execute(Pins_Entry%new_pin)#"INSERT INTO ATM_DEMO_PINS(PIN) VALUES(new_pin)"
mydb.commit()
/*
in string manipulation %s is use for input your variable to string so #it work as this
a=12
if use like this
print('my number %s',a)=>my number %s 12
but using this give your proper query
print('my number %s'%a)=>my number 12   
*/

Answered By: chanaka sandaruwan

You should do the following:

mycursor = mydb.cursor()
new_pin = int(input("Enter Pin Number:")) 
Pins_Entry = f"INSERT INTO ATM_DEMO_PINS(PIN) VALUES('{new_pin}')" 
mycursor.execute(Pins_Entry) 
mydb.commit()
Answered By: legalsniper1
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.