无法使用 MySQL 在 python 中插入单列值 [英] Can't insert single column value in python using MySQL
问题描述
我有一个单列表.我需要在此列中插入值.程序正确运行,没有错误.但是当我检查数据库时,没有插入任何内容.当我向代码和表中添加另一列时,程序正确插入数据.你能告诉我如何为单列表插入数据吗?这是不向表中插入任何内容的单列代码.
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()
这是两列代码.
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()
推荐答案
你需要去掉 %s
周围的引号,之后你需要知道 cursor 的第二个参数.execute()
是一个元组,写的是一个单元组:
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,))
这篇关于无法使用 MySQL 在 python 中插入单列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!