【问题标题】:python DELETE rows from mysql with REGEXP and mysql connector使用 REGEXP 和 mysql 连接器从 mysql 中删除行
【发布时间】:2014-09-26 10:46:47
【问题描述】:

根据此处找到的示例进行代码设置:

 for ICAO_COUNTRY in ['GM','DA','DT']:
  table='aerodrome'
  query = 'delete from %s where code_icao regexp "%s[A-Z][A-Z]"'
  cursor.execute(query,(table,ICAO_COUNTRY))

给出答案

Traceback (most recent call last):
  File "bin/cleanup2", line 22, in <module>
    cursor.execute(query,(table,ICAO_COUNTRY))
  File "/usr/lib/python2.7/dist-packages/mysql/connector/cursor.py", line 491, in execute
    self._handle_result(self._connection.cmd_query(stmt))
  File "/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line 635, in cmd_query statement))
  File "/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line 553, in _handle_result
    raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1064 (42000): 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 ''aerodrome' where code_icao regexp "'GM'[A-Z][A-Z]"' at line 1

在我看来,单引号被转移到 MySql 引擎,这不是我想要的。

【问题讨论】:

    标签: python mysql regex


    【解决方案1】:

    单引号会自动添加,因为您绑定的参数应该是字段、表名、值。但是你不能使用这种语法来进行字符串替换,它不同于带有占位符的基本格式化字符串

    您可以通过以下方式解决问题:

    for ICAO_COUNTRY in ['GM','DA','DT']:
      table='aerodrome'
      query = 'delete from %s where code_icao regexp \'' + ICAO_COUNTRY + '[A-Z][A-Z]\'' 
      cursor.execute(query, table)
    

    或者您可以将查询更改为

    query = 'delete from %s where code_icao regexp concat(%s, \'[A-Z][A-Z]\')'
    cursor.execute(query, (table,ICAO_COUNTRY)) 
    

    【讨论】:

    • 嗯,我真的相信 Python 不会强加这种不雅的编码。不过,这总比没有好。也就是说,如果它可以工作,但可惜它没有。
    • @Karlchen9:另一种方法是在查询中使用CONCAT
    • @Karlchen9:另一个问题,如果你在查询中使用双引号,你必须在 MySQL 中启用 ansi_quotes。如果不是这种情况,请尝试用单引号替换它们。
    猜你喜欢
    • 1970-01-01
    • 2016-08-17
    • 2015-03-15
    • 1970-01-01
    • 1970-01-01
    • 2016-09-21
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    相关资源
    最近更新 更多