How to get matched Rows from MySQLdb.cursors.Cursor python2.6

孤街浪徒 提交于 2019-12-09 20:29:47

问题


I'm working with python2.6 and MySQLdb. I have a table with this data

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

I want to do an mysql update like this example:

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

And I need to know if all the ids in the update exits in the database. My idea to get this information was to compare the number of items I tried to update vs the number of matched rows. In the example the numbers are 4 vs 3.

The problem is that i don't know how to get the "Matched Rows" from the cursor information. I only see this information in cursor._info = 'Rows matched: 3 Changed: 2 Warnings: 0'.

The cursor.rowcount is the number of changed rows, so =(

Thanks!


回答1:


If cursor._info contains that string, then you can just extract the 3 with a regex: re.search(r'Rows matched: (\d+)', cursor._info).group(1)

Alternatively, if you are using InnoDB tables (which support transactions), you can execute two queries: first just SELECT id FROM my_table WHERE id in (1,2,3,10001) and then get cursor.rowcount which will return the number of matching rows. Then execute your update. All queries run in the same cursors are part of the same transaction, so you are guaranteed that no other process will write the database between the queries.

Sources: see http://zetcode.com/databases/mysqlpythontutorial/




回答2:


The FOUND_ROWS option makes cursor.rowcount return the number of matched rows instead:

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

Docs:

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

(There's a typo in the MySQLdb docs. "client_flags" should be "client_flag")



来源:https://stackoverflow.com/questions/6852930/how-to-get-matched-rows-from-mysqldb-cursors-cursor-python2-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!