[英]Can't insert single column value in python using MySQL
我有一個列表。 我需要在此列中插入值。 程序運行正常,沒有錯誤。 但是當我檢查數據庫時,沒有插入任何內容。 當我在代碼和表中添加另一列時,程序正確地插入數據。 你能告訴我如何為單個列表插入數據嗎? 這是單列代碼,不會向表中插入任何內容。
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()
的第二個參數是一個元組,並且寫了一個元組:
(item,)
請注意逗號。 解決方案是:
sql="""INSERT INTO table (col1) VALUES (%s)"""
cursor.execute(sql, (x,))
您可以嘗試以下任何一種:
'%s'
,你可以使用?
代替 '%s'
,只使用沒有引號的%s
試試這個:
sql="""INSERT INTO table (col1) VALUES ({});""".format(x)
cursor.execute(sql)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.