How to use python variables in MySQL Insert statement, I am getting tuple error, please suggest

import MySQLdb
name="XYZ"
number=(256, 34576312114897154715004917944343995880721156274004613128261928143013598386679L)
db=MySQLdb.Connect("localhost","root","12345","phone")
cursor=db.cursor()
sql= ("""INSERT INTO phonebook(number, Mobile) VALUES(%s,%s)""" , name,number)
cursor.execute(sql)
db.commit()
db.close()

      

"Invalid processing format parameters;% s"% err) mysql.connector.errors.ProgrammingError: bad formatting formats; Python 'tuple' cannot be converted to MySQL type

+3


source to share


1 answer


your sql

varibale is a tuple

sql= ("""INSERT INTO phonebook(number, Mobile) VALUES(%s,%s)""" , name,number)

      

So when it tries to execute, cursor.execute(sql)

(where sql

is a tuple), it gives an error. Python 'tuple' cannot be converted to MySQL type



Use a string.

sql = """INSERT INTO phonebook(number, Mobile) VALUES(%s,%s)""" % (name,number)

      

+2


source







All Articles