![](/img/trans.png)
[英]Python, MySQL not inserting when using variable. Can use exact value of variable in place, and it works
[英]Python, A MySQL statement works when I put in actual value of variable, but not when using variable?
具有以下代碼,它是用於讀取stdin和處理日志的腳本的一部分。
jobId = loglist[19]
deliveryCount += 1
dbcur.execute('UPDATE campaign_stat_delivered SET pmta_delivered = pmta_delivered + %s WHERE id = %s') % (deliveryCount,jobId)
dbcon.commit()
dbcon.close()
我可以運行以下命令:
dbcur.execute('UPDATE campaign_stat_delivered SET pmta_delivered = pmta_delivered + 1 WHERE id=1')
dbcon.commit()
dbcon.close()
它會工作。 我不太確定發生了什么,而且我很難快速測試,因為我的程序直接將腳本輸入其中,因此我實際上看不到腳本在運行。 我必須進行更改,重新啟動供稿的程序,發送電子郵件,然后檢查數據庫。 擁有其他腳本,並且能夠毫無問題地在SQL語句中使用變量。
關於可能發生的事情有什么建議嗎? 而且,關於如何更快進行測試的任何建議?
完整代碼:
import os
import sys
import time
import MySQLdb
import csv
if __name__=="__main__":
dbcon = MySQLdb.connect(host="tattoine.mktrn.net", port=3306, user="adki", passwd="pKhL9vrMN8BsFrJ5", db="adki")
dbcur = dbcon.cursor()
#type, timeLogged,timeQueued,orig,rcpt,orcpt,dsnAction,dsnStatus,dsnDiag,dsnMta,bounceCat,srcType,srcMta,dlvType,dlvSourceIp,dlvDestinationIp,dlvEsmtpAvailable,dlvSize,vmta,jobId,envId,queue,vmtaPool
while True:
line = sys.stdin.readline()
fwrite = open("debug.log","w")
# fwrite.write(str(deliveryCount))
fwrite.write("test2")
dbcur.execute("INSERT INTO test(event_type) VALUES ('list')")
dbcon.commit()
loglist = line.split(',')
deliveryCount = 0
bounceType = loglist[0]
bounceCategory = loglist[10]
email = loglist[4]
jobId = loglist[19]
if bounceType == 'd':
deliveryCount += 1
fwrite = open("debug2.log","w")
# fwrite.write(str(deliveryCount))
fwrite.write("test3")
dbcur.execute("INSERT INTO test(event_type) VALUES (%d)", deliveryCount)
dbcon.commit()
dbcur.execute('UPDATE campaign_stat_delivered SET pmta_delivered = pmta_delivered + %s WHERE id = %s',(deliveryCount,jobId))
dbcon.commit()
dbcon.close()
切勿使用字符串插值來運行sql查詢。
你應該做:
dbcur.execute(
'UPDATE campaign_stat_delivered SET pmta_delivered = pmta_delivered + %s WHERE id = %s',
(deliveryCount,jobId)
)
execute函數有兩個參數。 帶占位符和參數元組的查詢。 這樣,mysql將為您轉義參數並防止sql注入攻擊( http://en.wikipedia.org/wiki/SQL_injection )
您的錯誤一定是由於您對查詢'UPDATE campaign_stat_delivered SET pmta_delivered = pmta_delivered + %s WHERE id = %s'
的結果使用了%運算符。 在語法上,此查詢本身(不帶參數)在語法上不正確。 您必須將參數的元組作為第二個參數傳遞給execute函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.