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

元气小坏坏 提交于 2019-12-04 17:17:17

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/

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")

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