How can I do begin transaction in pymysql ? (mysql)

情到浓时终转凉″ 提交于 2019-12-07 05:22:16

问题


I want to use run below mysql script using with pymysql.

START TRANSACTION;
BEGIN;
insert into ~~~ 
COMMIT;

my python source code is

connection = pymysql.connect(~~~~~~~)
     with connection.cursor() as cursor :
         connection.begin()
         cursor.execute(~~.sql)
         connection.commit()
connection.close()

My question is "connection.begin()" is the same thing "START TRANSACTION; BEGIN;" ? I want to use "START TRANSACTION; BEGIN;"


回答1:


According to the PyMySQL docs/example (singular...this doesn't seem like a very well-supported package), by default auto-commit is off, so you do need to run connection.commit() to actually finish the transaction.

Their example:

import pymysql.cursors

connection = pymysql.connect(host='localhost',
                             user='user',
                             password='passwd',
                             db='db',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

try:
    with connection.cursor() as cursor:
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, ('webmaster@python.org', 'very-secret'))

    # connection is not autocommit by default. So you must commit to save changes.
    connection.commit()

finally:
    connection.close()


来源:https://stackoverflow.com/questions/38298152/how-can-i-do-begin-transaction-in-pymysql-mysql

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