Python MYSQL更新语句

Ada*_*nik 41 python mysql mysql-python sql-parametrized-query

我正在尝试使这个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)   
Run Code Online (Sandbox Code Playgroud)

我出错的任何想法?

Est*_*ber 76

应该是:

cursor.execute ("""
   UPDATE tblTableName
   SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s
   WHERE Server=%s
""", (Year, Month, Day, Hour, Minute, ServerID))
Run Code Online (Sandbox Code Playgroud)

可以用基本的字符串操作来做,

cursor.execute ("UPDATE tblTableName SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s WHERE Server='%s' " % (Year, Month, Day, Hour, Minute, ServerID))
Run Code Online (Sandbox Code Playgroud)

但是这种方式是不鼓励的,因为它让你打开SQL注入.由于它是如此简单(以及类似)做了正确的方式TM.做得对.

唯一要注意的是,一些数据库后端不遵循相同的字符串替换约定(SQLite会想到).

  • 保罗的答案更好.http://stackoverflow.com/questions/1307378/python-mysql-update-statement/1307413#1307413 (6认同)
  • 做*不*这样做.你让自己对SQL注入攻击持开阔态度.Paulo有正确的答案,因为它确保在将值传递给数据库之前正确转义这些值. (6认同)
  • 扯掉Paolo的答案,因为我无法删除已接受的答案. (3认同)

Pao*_*ino 50

你的语法都错了:

cursor.execute ("""
   UPDATE tblTableName
   SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s
   WHERE Server=%s
""", (Year, Month, Day, Hour, Minute, ServerID))
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请阅读文档.


Lit*_*oys 19

这是正确的方法:

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()
Run Code Online (Sandbox Code Playgroud)

PS不要忘记connect.commit(),否则它将无法正常工作

  • 没有提交它不起作用,我使用python 3.5 (3认同)