Ways to avoid MySQLdb's “Commands out of sync; you can't run this command now” (2014) exception

后端 未结 1 1223
情歌与酒
情歌与酒 2020-12-10 03:13

Following code, using python 2.6.6 and MySQLdb 1.2.2 causes Commands out of sync; you can\'t run this command now MySQLdb exception:

import MySQLdb
         


        
相关标签:
1条回答
  • 2020-12-10 03:37

    DB-API tries to handle transactions on its own, starting a transaction on the first command and having its own API call to commit it, so:

    cursor.execute( "CREATE TABLE t1 ( t1_id INT PRIMARY KEY AUTO_INCREMENT )" )
    cursor.commit()
    cursor.execute( "CREATE TABLE t2 ( t2_id INT PRIMARY KEY AUTO_INCREMENT )" )
    cursor.commit()
    

    In my opinion, this is a serious, glaring design error of Python's DB-API, making it a serious hassle to execute commands outside of transactions and to have proper control over transactions, eg. to use things like SQLite's BEGIN EXCLUSIVE TRANSACTION. It's as if someone with no real database experience was allowed to design the API...

    0 讨论(0)
提交回复
热议问题