python torndb
2019-05-29 20:31
295 查看
最近接触的项目中数据库操作使用python 的 torndb库
torndb 基于 pymysql
遇到的问题:
pymysql 创建Connection对象时,autocommit 参数默认为False, 所以可以使用try catch 的结构,当数据操作发生错误时进行回滚 。
torndb 创建Connection对象时,调用了torndb中的 reconnect函数,这个函数在首先关闭现有的连接,然后重新创建链接,同时会把autocommit属性改为True.所以使用torndb时,要使用Connection的begin() 方法开启事务,相当于在数据库中直接使用start transaction 命令。或者修改connection.autocommit=False,使其支持回滚。
事务的四个特性: ACID , 原子性, 一致性, 独立性,持久性。
torndb源码:
def __init__(self, host, database, user=None, password=None, max_idle_time=7 * 3600, connect_timeout=3, time_zone="+8:00", charset="utf8", sql_mode="TRADITIONAL", **kwargs): self.host = host self.database = database self.max_idle_time = float(max_idle_time) args = dict(charset=charset, db=database, init_command=('SET time_zone = "%s"' % time_zone), connect_timeout=connect_timeout, sql_mode=sql_mode, **kwargs) if user is not None: args["user"] = user if password is not None: args["passwd"] = password # We accept a path to a MySQL socket file or a host(:port) string if "/" in host: args["unix_socket"] = host else: self.socket = None pair = host.split(":") if len(pair) == 2: args["host"] = pair[0] args["port"] = int(pair[1]) else: args["host"] = host args["port"] = 3306 self._db = None self._db_args = args self._last_use_time = time.time() try: self.reconnect() # 调用 reconnect 方法 except Exception: logging.error("Cannot connect to MySQL on %s", self.host, exc_info=True) def reconnect(self): """Closes the existing database connection and re-opens it.""" self.close() self._db = pymysql.connect(**self._db_args) self._db.autocommit(True) # 修改了 autocommit 属性
相关文章推荐
- python torndb使用简介
- Python开发【模块】:torndb
- 解决torndb(目前对MySQLdb最好的封装)在python3.x下不能用的问题
- Python中MySQLdb和torndb模块对MySQL的断连问题处理
- Python中MySQLdb和torndb模块对MySQL的断连问题处理
- python3.x的torndb使用记录(发现网上没有关于torndb的使用说明,可能太简单了吧:-P)
- Ubuntu下安装python的torndb开发环境
- Python计算机视觉:第六章 图像聚类
- XGBoost-Python完全调参指南-参数解释篇
- 二分k均值 Python实现
- 【原】Learning Spark (Python版) 学习笔记(四)----Spark Sreaming与MLlib机器学习
- python复制目录
- python3 pymysql 'latin-1' codec can't encode character 错误 问题解决
- 【python小程序】登录及信息查询系统
- python换行写入文件
- Python数据结构——链表
- python的全局变量与局部变量
- python 爬虫‘Max retries exceeded with url’错误
- python实现决策树
- 【python】List与string转化--test_veh.py代码