【问题标题】:How to get matched Rows from MySQLdb.cursors.Cursor python2.6如何从 MySQLdb.cursors.Cursor python2.6 中获取匹配的行
【发布时间】:2011-10-14 17:45:51
【问题描述】:

我正在使用 python2.6 和 MySQLdb。我有一张包含这些数据的表格

+----+--------+
| id | status |
+----+--------+
| 1  |     A  |
| 2  |     B  |
| 3  |     B  |
+----+--------+

我想做一个类似这个例子的mysql更新:

UPDATE my_table SET status = "A" where id in (1,2,3,10001);
Query OK, 2 rows affected (0.03 sec)
Rows matched: 3  Changed: 2  Warnings: 0

而且我需要知道更新中的所有 id 是否都存在于数据库中。我获取此信息的想法是比较我尝试更新的项目数与匹配行数。在示例中,数字是 4 对 3。

问题是我不知道如何从光标信息中获取“匹配行”。我只在 cursor._info = 'Rows matching: 3 Changed: 2 Warnings: 0' 中看到此信息。

cursor.rowcount是改变的行数,所以=(

谢谢!

【问题讨论】:

    标签: python cursor mysql-python rowcount


    【解决方案1】:

    如果 cursor._info 包含该字符串,那么您可以使用正则表达式提取 3:re.search(r'Rows matched: (\d+)', cursor._info).group(1)

    或者,如果您使用 InnoDB 表(支持事务),您可以执行两个查询:首先只是 SELECT id FROM my_table WHERE id in (1,2,3,10001),然后获取 cursor.rowcount,它将返回匹配的行数。然后执行你的更新。在同一个游标中运行的所有查询都是同一个事务的一部分,因此可以保证在查询之间没有其他进程会写入数据库。

    来源:见http://zetcode.com/databases/mysqlpythontutorial/

    【讨论】:

      【解决方案2】:

      FOUND_ROWS 选项使 cursor.rowcount 返回匹配的行数:

      db_connection = MySQLdb.connect(
              host = settings['dbHost'],
              user = settings['dbUser'],
              passwd = settings['dbPass'],
              db = settings['dbName'],
              client_flag = MySQLdb.constants.CLIENT.FOUND_ROWS
              )
      

      文档:

      http://mysql-python.sourceforge.net/MySQLdb-1.2.2/public/MySQLdb.constants.CLIENT-module.html http://dev.mysql.com/doc/refman/5.6/en/mysql-real-connect.html

      (MySQLdb 文档中有一个错字。“client_flags”应该是“client_flag”)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-10-04
        • 2014-01-23
        • 1970-01-01
        • 1970-01-01
        • 2019-05-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多