【发布时间】:2017-06-27 10:13:25
【问题描述】:
我有一个关于 MySQL 和事务的问题。我使用 MySQL 5.7.18、python 3 和 Oracle mysql 连接器 v2.1.4
我不明白两者之间的区别 a) 有一个事务并且——如果发生错误——回滚和 b) 没有事务并且——如果发生错误——根本不提交更改。
两者似乎都给我留下了完全相同的结果(即表中没有条目,请参见下面的代码示例)。这是否与使用 InnoDB 有关——否则结果会有所不同吗?
如果使用事务有什么好处? 1) 我无法回滚已提交的更改并且 2) 我也可以不提交更改(直到我完成我的任务或确定某些查询没有引发任何异常)?
我曾尝试在https://downloads.mysql.com/docs/connector-python-en.a4.pdf 中找到这些问题的答案,但未能找到本质区别。
有人问了一个几乎相同的问题并收到了一些回复,但我认为这些回复实际上并不包含答案:Mysql transaction : commit and rollback 回复的重点是打开多个连接和更改可见性。仅此而已吗?
import mysql.connector
# Connect to MySQL-Server
conn = mysql.connector.connect(user='test', password='blub',
host='127.0.0.1', db='my_test')
cursor = conn.cursor(buffered=True)
# This is anyway the default in mysql.connector
# cursor.autocommit = False
sql = """CREATE TABLE IF NOT EXISTS `my_test`.`employees` (
`emp_no` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(14) NOT NULL,
PRIMARY KEY (`emp_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8"""
try:
cursor.execute(sql)
conn.commit()
except:
print("error")
# Arguments on default values
# conn.start_transaction(consistent_snapshot=False,
# isolation_level=None, readonly=False)
sql = """INSERT INTO `my_test`.`employees`
(`first_name`)
VALUES
(%s);"""
employees = {}
employees["1"] = ["Peter"]
employees["2"] = ["Bruce"]
for employee, value in employees.items():
cursor.execute(sql, (value[0],))
print(conn.in_transaction)
# If I do not commit the changes, table is left empty (whether I write
# start_transaction or not)
# If I rollback the changes (without commit first), table is left empty
# (whether I write start_transaction or not)
# If I commit and then rollback, the rollback had no effect (i.e. there are
# values in the table (whether I write start_transaction or not)
conn.commit()
conn.rollback()
非常感谢您提前提供的帮助!我很感激。
【问题讨论】:
标签: python mysql sql python-3.x transactions