我試圖讓這個Python的MYSQL更新語句正確的是(使用變量):Python的MYSQL更新語句
cursor.execute ("UPDATE tblTableName SET Year=%s" % Year ", Month=%s" % Month ", Day=%s" % Day ", Hour=%s" % Hour ", Minute=%s" Minute "WHERE Server=%s " % ServerID)
任何想法,我要去哪裏錯了嗎?
我試圖讓這個Python的MYSQL更新語句正確的是(使用變量):Python的MYSQL更新語句
cursor.execute ("UPDATE tblTableName SET Year=%s" % Year ", Month=%s" % Month ", Day=%s" % Day ", Hour=%s" % Hour ", Minute=%s" Minute "WHERE Server=%s " % ServerID)
任何想法,我要去哪裏錯了嗎?
cursor.execute ("""
UPDATE tblTableName
SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s
WHERE Server=%s
""", (Year, Month, Day, Hour, Minute, ServerID))
可以也基本字符串操作去做,
cursor.execute ("UPDATE tblTableName SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s WHERE Server='%s' " % (Year, Month, Day, Hour, Minute, ServerID))
但this way is discouraged because it leaves you open for SQL Injection。因爲它很容易(和類似)做到這一點正確的方式tm。正確地做。
你應該小心的唯一的事情是,一些數據庫後端不遵循相同的約定進行字符串替換(SQLite浮現)。
你已經得到了所有的語法錯誤:
cursor.execute ("""
UPDATE tblTableName
SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s
WHERE Server=%s
""", (Year, Month, Day, Hour, Minute, ServerID))
如需更多信息,read the documentation。
+1你比我快:) – 2009-08-20 16:38:06
這應該是被接受的答案。 – 2015-08-14 02:54:10
這是正確的方式:
import MySQLdb
if __name__ == '__main__':
connect = MySQLdb.connect(host="localhost", port=3306,
user="xxx", passwd="xxx", db='xxx', charset='utf8')
cursor = connect.cursor()
cursor.execute("""
UPDATE tblTableName
SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s
WHERE Server=%s
""", (Year, Month, Day, Hour, Minute, ServerID))
connect.commit()
connect.close()
附:不要忘記connect.commit()
,否則它不會工作
由於某種原因,它們都不適合我。
我明白,由於某些原因,python不會讀取%s。所以在你的SQL代碼中使用(?)代替%S。
最後這對我有用。
cursor.execute ("update tablename set columnName = (?) where ID = (?) ",("test4","4"))
cursor.commit()
保羅的回答比較好。 http://stackoverflow.com/questions/1307378/python-mysql-update-statement/1307413#1307413 – voyager 2009-08-20 16:37:37
但是,這一個將與每個後端工作。該版本不會對輸入進行任何驗證,而Paolo的方式將確保逃避變量內容。 – voyager 2009-08-20 16:39:26
做*不*這樣做。您將自己留給SQL注入攻擊。 Paulo有正確的答案,因爲它確保在將值傳遞給數據庫之前,這些值已正確地轉義。 – 2009-08-20 19:19:24