Search code examples
pythonstring-formattingmysql-python

Formatting python string within a string


I am using Python MySQL connector, need to write a SQL query as:

update inventory set checked_out = 'n' where item = 'dongle'

All the items are placed in a Cursor from a previous execution, i'm using in a loop as :

cnx = mysql.connector.connect(host='localhost',database='mem_bug',user='root',password='July@2013')
for r in cursor :
   sql = "update inventory set checked_out = 'n' where item = {}".format(r[0])
   cursor.execute(sql)
   cnx.commit()

When SQL is formed it is formed as :

update inventory set checked_out = 'n' where item = dongle

Hence gives the error as :

_mysql_connector.MySQLInterfaceError: Unknown column 'dongle' in 'where clause'

How can I format string within the string to get my SQL rightly executed.


Solution

  • Just add quotation mark and it seems the problem:

    cnx = mysql.connector.connect(host='localhost',database='mem_bug',user='root',password='July@2013')
    for r in cursor :
       sql = "update inventory set checked_out = 'n' where item = '{}'".format(r[0])
       cursor.execute(sql)
       cnx.commit()