Can't insert single column value in python using MySQL

mysql, python, python-2.7, sql

Solution

You need to lose the quotes around `%s`, after that you need to know that the second argument to `cursor.execute()` is a tuple, and that a one-tuple is written:

(item,)

note the comma. The solution is then:

sql="""INSERT INTO table (col1) VALUES (%s)"""
cursor.execute(sql, (x,))

Problem

I have a single column table. I need to insert values in this column. The program runs correctly without errors. But when I check the database, nothing gets inserted. When I added another column to the code and table, the program inserts data correctly. Can you tell me how to insert data for a single column table? This is the single column code that does not insert anything to the table. ``` import MySQLdb conn = MySQLdb.connect(host= "localhost", user="root", passwd="123", db="dbname") cursor = conn.cursor() x=100 try: sql="""INSERT INTO table (col1) VALUES ('%s')""" cursor.execute(sql, (x)) conn.commit() except: conn.rollback() conn.close() ``` This is the two columns code. ``` import MySQLdb conn = MySQLdb.connect(host= "localhost", user="root", passwd="123", db="dbname") cursor = conn.cursor() x=100 y=2 try: sql="""INSERT INTO table (col1,col2) VALUES ('%s','%s')""" cursor.execute(sql, (x,y)) conn.commit() except: conn.rollback() conn.close() ```

Original source