Python Mysqldb D

2024-06-02 15:33:51 发布

您现在位置:Python中文网/ 问答频道 /正文

出于某种原因,这是爆炸:

print tbl,record
statmt="DELETE FROM '%s' WHERE email LIKE '%s'" %(tbl,record)
print statmt
self.cursor.execute(statmt)

错误:

maillist_frogs test@testovich.com
DELETE FROM 'maillist_frogs' WHERE email LIKE 'test@testovich.com'
Traceback (most recent call last):
  File "./compare.py", line 123, in <module>
    main()
  File "./compare.py", line 117, in main
    remove_mailgust = sql_mailgust.removeRow ("maillist_frogs",x)
  File "./compare.py", line 81, in removeRow
    self.cursor.execute(statmt)
  File "build/bdist.macosx-10.6-intel/egg/MySQLdb/cursors.py", line 174, in execute
  File "build/bdist.macosx-10.6-intel/egg/MySQLdb/connections.py", line 36, in defaulterrorhandler
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''maillist_frogs' WHERE email LIKE 'test@testovich.com'' at line 1")

谢谢!!:)


Tags: inpytestcomexecuteemaillinewhere
3条回答
def removeRow(self,tbl,record):
        """ Remove specific record """
        record = record[0]
        statmt="DELETE FROM %s WHERE email LIKE '%s'" %(tbl,record)
        self.cursor.execute(statmt)

我刚才也有类似的问题。

在进一步的研究之后,我意识到我忘记了在删除之后做一个connection.commit(),或者,正如我在其他地方发现的那样,如果不需要控制事务提交,您可以在执行任何其他数据操作之前做cursor.execute("set autocommit = 1"),让它们立即自动提交。

这可能是Cmag代码的问题,不过如果看不到更多,就很难说了。

你有两个问题:

第一个是导致崩溃的原因,是您引用了表名,并使用了常规引号。如果要引用表名,则应使用反引号(`)。

第二个问题,你“做得不对”。您不应该使用字符串格式创建查询,而应该让Python MySQLdb的cursor.execute为您正确地创建查询。

为此,请尝试以下操作:

statmt = "DELETE FROM %s WHERE email LIKE %s" 
self.cursor.execute(statmt, (tbl, record))

顺便说一句,在MySQLdb查询中使用字符串格式会使您暴露在SQL注入中,以防在Web上或其他地方使用应用程序。您不应该使用字符串格式来创建查询。

相关问题 更多 >