mysql.connector事务总结:

connection.autocommit = 0 (默认值)

事务处理

使用 connection.commit()方法

#!/usr/bin/env python
# -*- coding:utf-8 -*- '''mysql.connector事务总结: connection.autocommit = 0 (默认值)
事务处理
使用 connection.commit()方法 分析:
智能commit状态:
connection.autocommit = 0 (默认值)
默认不提交
事务处理
可以使用 connection.commit()方法来进行提交 自动commit状态:
connection.autocommit = 0
这样,在任何DML操作时,都会自动提交
事务处理
connection.execute("BEGIN;")
connection.commit()
如果不使用事务, 批量添加数据相对缓慢 两种方式, 事务耗时差别不大
自动commit的速度受网络传输影响大 比较数据:
192.168.1.107, count=100
默认commit事务耗时: 0.152
自动commit, cursor.execute("COMMIT;")耗时: 0.139
自动commit2, connection.commit()耗时: 0.143
自动commit,非事务耗时: 0.397 192.168.1.107, count=1000
默认commit事务耗时: 1.365
自动commit, cursor.execute("COMMIT;")耗时: 1.389
自动commit2, connection.commit()耗时: 1.291
自动commit,非事务耗时: 3.871 192.168.6.226, count=100
默认commit事务耗时: 0.178
自动commit, cursor.execute("COMMIT;")耗时: 0.183
自动commit2, connection.commit()耗时: 0.192
自动commit,非事务耗时: 1.965 ''' import sys
import time class Elapse_time(object):
'''耗时统计工具'''
def __init__(self, prompt=''):
self.prompt = prompt
self.start = time.time() def __del__(self):
print('%s耗时: %.3f' % (self.prompt, time.time() - self.start))
CElapseTime = Elapse_time import mysql.connector # -------------------------------------------------------------------------------
# 测试
# db_parameters = {'host': '192.168.1.107',
'database': 'test',
'charset': 'utf8'}
db_parameters1 = {'host': '192.168.6.226',
'database': 'test',
'charset': 'utf8'} def prepare(isolation_level = ''):
connection = mysql.connector.MySQLConnection(**db_parameters)
cursor = connection.cursor()
cursor.execute("create table IF NOT EXISTS people (num int, age int)")
cursor.execute('delete from people')
connection.commit()
return connection, connection.cursor() def db_insert_values(cursor, count):
num = 1
age = 2 * num while num <= count:
cursor.execute("insert into people values (%s, %s)", (num, age))
num += 1
age = 2 * num def study_case1_default_commit_manual(count):
connection, cursor = prepare() elapse_time = Elapse_time(' 默认commit事务')
db_insert_values(cursor, count)
connection.commit() cursor.execute("select count(*) from people")
print (cursor.fetchone()) def study_case2_autocommit_transaction(count):
connection, cursor = prepare(isolation_level = None)
connection.autocommit = 1 elapse_time = Elapse_time(' 自动commit, cursor.execute("COMMIT;")')
cursor.execute("BEGIN;") # 关键点
db_insert_values(cursor, count)
cursor.execute("COMMIT;") #关键点 cursor.execute("select count(*) from people;")
print (cursor.fetchone()) def study_case3_autocommit_transaction2(count):
connection, cursor = prepare(isolation_level = None)
connection.autocommit = 1 elapse_time = Elapse_time(' 自动commit2, connection.commit()')
cursor.execute("BEGIN;") # 关键点
db_insert_values(cursor, count)
connection.commit() cursor.execute("select count(*) from people;")
print (cursor.fetchone()) def study_case4_autocommit_no_transaction(count):
connection, cursor = prepare(isolation_level = None)
connection.autocommit = 1 elapse_time = Elapse_time(' 自动commit,非事务')
db_insert_values(cursor, count) cursor.execute("select count(*) from people;")
print (cursor.fetchone()) def main(config):
output = []
db = mysql.connector.Connect(**config)
cursor = db.cursor() # Drop table if exists, and create it new
stmt_drop = "DROP TABLE IF EXISTS names"
cursor.execute(stmt_drop) stmt_create = """
CREATE TABLE names (
id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(30) DEFAULT '' NOT NULL,
cnt TINYINT UNSIGNED DEFAULT 0,
PRIMARY KEY (id)
) ENGINE=InnoDB"""
cursor.execute(stmt_create) warnings = cursor.fetchwarnings()
if warnings:
ids = [ i for l,i,m in warnings]
output.append("Oh oh.. we got warnings..")
if 1266 in ids:
output.append("""
Table was created as MYISAM, no transaction support. Bailing out, no use to continue. Make sure InnoDB is available!
""")
db.close()
return # Insert 3 records
output.append("Inserting data")
names = ( ('Geert',), ('Jan',), ('Michel',) )
stmt_insert = "INSERT INTO names (name) VALUES (%s)"
cursor.executemany(stmt_insert, names) # Roll back!!!!
output.append("Rolling back transaction")
db.rollback() # There should be no data!
stmt_select = "SELECT id, name FROM names ORDER BY id"
cursor.execute(stmt_select)
rows = None
try:
rows = cursor.fetchall()
except mysql.connector.InterfaceError as e:
raise if rows == []:
output.append("No data, all is fine.")
else:
output.append("Something is wrong, we have data although we rolled back!")
output.append(rows)
cursor.close()
db.close()
return output # Do the insert again.
cursor.executemany(stmt_insert, names) # Data should be already there
cursor.execute(stmt_select)
output.append("Data before commit:")
for row in cursor.fetchall():
output.append("%d | %s" % (row[0], row[1])) # Do a commit
db.commit() cursor.execute(stmt_select)
output.append("Data after commit:")
for row in cursor.fetchall():
output.append("%d | %s" % (row[0], row[1])) # Cleaning up, dropping the table again
cursor.execute(stmt_drop) cursor.close()
db.close()
return output if __name__ == '__main__':
#out = main(db_parameters)
#print('\n'.join(out)) count = 1000
prepare()
for i in range(1):
study_case1_default_commit_manual(count)
study_case2_autocommit_transaction(count)
study_case3_autocommit_transaction2(count)
study_case4_autocommit_no_transaction(count)

mysql.connector 事务总结的更多相关文章

  1. mysql 分布式事务

    php + mysql 分布式事务 事务(Transaction)是访问并可能更新数据库中各种数据项的一个程序执行单元: 事务应该具有4个属性:原子性.一致性.隔离性.持续性 原子性(atomicit ...

  2. Mybatis异常处理之MySQL Connector Java] will not be managed by Spring

    很长时间没写后台代码有点生疏了,这不今天又出点小插曲,写个文章记录下. 由于要上传点数据到后台,顺手整了个mybatis+springmvc.在保存数据时出现了异常. Creating a new S ...

  3. MySQL Connector/Python 接口 (一)

    这里仅介绍 MySQL 官方开发的 Python 接口,参见这里: https://dev.mysql.com/doc/connector-python/en/ Chapter 1 Introduct ...

  4. MySQL 数据库事务与复制

    好久没有写技术文章了,因为一直在思考 「后端分布式」这个系列到底怎么写才合适. 最近基本想清楚了,「后端分布式」包括「分布式存储」和 「分布式计算」两大类. 结合实际工作中碰到的问题,以寻找答案的方式 ...

  5. 创建ASP.NET Core MVC应用程序(2)-利用MySQL Connector NET连接到MySQL

    创建ASP.NET Core MVC应用程序(2)-利用MySQL Connector NET连接到MySQL 用惯.NET的研发人员都习惯性地使用SQLServer作为数据库.然而.NET Core ...

  6. vc++2013中使用MySQL connector/C++ 1.1.4静态链接报错

    包含头文件 #include <mysql_connection.h> #include <mysql_driver.h> #include <cppconn/state ...

  7. Using MySQL Connector .NET 6.6.4 with Entity Framework 5

    I had been waiting for the latest MySQL connector for .NET to come out so I can move on to the new a ...

  8. [转]MySQL Connector/C++(一)

    http://www.cnblogs.com/dvwei/archive/2013/04/18/3029464.html#undefined#undefined MySQL Connector/C++ ...

  9. mysql.connector操作mysql的blob值

    This tutorial shows you how to work with MySQL BLOB data in Python, with examples of updating and re ...

随机推荐

  1. Percona Xtrabackup备份及恢复

    1. http://www.percona.com/software/percona-xtrabackup下载并安装 2. 全量备份  a.全量备份到制定目录            innobacku ...

  2. 模拟人的手指在UI上滑动时3D模型跟随着移动(Unity)

    问题: 怎么让当手指滑动的同时对应的模型发生旋转 解决办法: 1:通过控制摄像机或者模型来实现效果 2:通过获取鼠标移动时X轴Y轴的偏移量来确定模型的旋转角度 3:为了不让人感觉到突兀,建议使用Mat ...

  3. html 报告页面样式

    修改了下HTML页面样式 页面代码 <!DOCTYPE html> <html lang="en"> <head> <meta chars ...

  4. eas之怎么设置单据保存或者提交完不跳到下个新增页面

    this.chkMenuItemSubmitAndAddNew.setSelected(false);

  5. eas之获取单据编码规则

    //获取单据编码规则  /*** @Title: getNumber* @Description: TODO(获取单据编码规则)*               <p>* @date 201 ...

  6. eas之获得任何一个KDTable的选中行

    import com.kingdee.bos.ctrl.kdf.table.util.KDTableUtil; int[] selectRows =KDTableUtil.getSelectedRow ...

  7. 【Shell编程】Shell程序设计

    1.Shell简介   作为Linux灵感来源的Unix系统最初是没有图形化界面的,所有的任务都是通过命令行来实现的.因此,Unix的命令行系统得到了很大的发展,逐步成为一个功能强大的系统.   Sh ...

  8. [luogu2414 NOI2011]阿狸的打字机 (AC自动机)

    传送门 Solution 我们知道AC自动机上如果有一点A的fail[A]->B那么B为A的一个后缀 那么我们的问题\((x,y)\)就变为在y中有多少个点直接或间接连向x的终止节点 如果写暴力 ...

  9. 邓_ Phpcms·二次开发

    PHPCMS V9产品介绍 PHPCMS V9(简称V9)采用PHP5+MYSQL做为技术基础进行开发.V9采用OOP(面向对象)方式进行基础运行框架搭建.模块化开发方式做为功能开发形式.框架易于功能 ...

  10. PHP学习总结(14)——PHP入门篇之常用运算符

    一.什么是运算符 什么是运算符?运算符是告诉PHP做相关运算的标识符号.例如,你需要计算123乘以456等于多少,这时候就需要一个符号,告诉服务器,你需要做乘法运算. PHP中的运算符有哪些?PHP运 ...