问题
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()
回答1:
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,))
回答2:
You can try either of these:
- Don't use
'%s', you can use?instead - Instead of
'%s', just use%swithout quotes
回答3:
try this:
sql="""INSERT INTO table (col1) VALUES ({});""".format(x)
cursor.execute(sql)
来源:https://stackoverflow.com/questions/41309096/cant-insert-single-column-value-in-python-using-mysql