Correct exception handling with python MySQLdb connection

前端 未结 1 1624
星月不相逢
星月不相逢 2021-02-13 19:29

I created a small/basic python script to insert data into a MySQL database. I included some error handling - mainly to close the connection and/or prevent hanging connections in

相关标签:
1条回答
  • 2021-02-13 20:20

    I believe the issue was I wasn't invoking conn.rollback() in the except clause (and consequently, the connection was not closing properly). One line (see below) seemed to fix the issue (I can't be exactly sure if that was this issue - if someone could confirm that would be great).

    conn=MySQLdb.connect(host=####, user=####, passwd=####, db=####)
    curs=conn.cursor()
    try:
        curs.execute(sql)
        conn.commit()           
    
    except MySQLdb.Error as e:
        conn.rollback()              #rollback transaction here
        if e[0]!= ###:
            raise
    
    finally: 
        curs.close()    
        conn.close()
    
    0 讨论(0)
提交回复
热议问题