python MySQLdb 一个连接connection多个cursor
使用MySQLdb时,如果创建一个连接connection,多个线程同时使用,会不会有问题?
在下文中,我们将模拟这种场景,看是否会出现问题。
1.示例
1.1 正常的情况
创建一个连接,两个线程同时使用这个连接,生成游标cursor,进行查询,并输出结果。
程序启动后,让线程1睡眠1s,保证让线程2线执行。
import MySQLdb
import threading
import timedef get_connection():host = "127.0.0.1"port = 3306user = "root"passwd = "Aa123456"conn = MySQLdb.connect(host=host, port=port, user=user,passwd=passwd, connect_timeout=2, charset="utf8")return conndef thread1_runtime(conn, sql):time.sleep(1)cursor = conn.cursor()cursor.execute(sql)ret = cursor.fetchone()thread_name = threading.current_thread().nameprint("thread name:%s, ret:%s" %(thread_name, ret))def thread2_runtime(conn, sql):cursor = conn.cursor()cursor.execute(sql)ret = cursor.fetchone()thread_name = threading.current_thread().nameprint("thread name:%s, ret:%s" %(thread_name, ret))if __name__ == "__main__":thread1_sql = "select 1"thread2_sql = "select 2"conn = get_connection()thread1 = threading.Thread(target=thread1_runtime, name="thread 001", args=(conn, thread1_sql))thread2 = threading.Thread(target=thread2_runtime, name="thread 002", args=(conn, thread2_sql))thread1.start()thread2.start()thread1.join()thread2.join()print("...main exit....")
从结果可以看到,一切正常。
output:
thread name:thread 002, ret:(2,)
thread name:thread 001, ret:(1,)
…main exit…
1.2 异常的情况
以下例子中,程序启动后,线程1和线程2使用同一连接创建新的游标cursor,执行查询。
接着,线程1睡眠1秒,线程2睡眠2秒。
最后各自打印查询结果。
import MySQLdb
import threading
import timedef get_connection():host = "127.0.0.1"port = 3306user = "root"passwd = "Aa123456"conn = MySQLdb.connect(host=host, port=port, user=user,passwd=passwd, connect_timeout=2, charset="utf8")return conndef thread1_runtime(conn, sql):cursor = conn.cursor()cursor.execute(sql)time.sleep(1)ret = cursor.fetchone()thread_name = threading.current_thread().nameprint("thread name:%s, ret:%s" %(thread_name, ret))def thread2_runtime(conn, sql):cursor = conn.cursor()cursor.execute(sql)time.sleep(2)ret = cursor.fetchone()thread_name = threading.current_thread().nameprint("thread name:%s, ret:%s" %(thread_name, ret))if __name__ == "__main__":thread1_sql = "select 1"thread2_sql = "select 2"conn = get_connection()thread1 = threading.Thread(target=thread1_runtime, name="thread 001", args=(conn, thread1_sql))thread2 = threading.Thread(target=thread2_runtime, name="thread 002", args=(conn, thread2_sql))thread1.start()thread2.start()thread1.join()thread2.join()print("...main exit....")
output:
Exception in thread thread 002:
Traceback (most recent call last):
File “/usr/local/Cellar/python/3.6.4_4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py”, line 916, in _bootstrap_inner
self.run()
File “/usr/local/Cellar/python/3.6.4_4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py”, line 864, in run
self._target(*self._args, **self._kwargs)
File “one_conn_mutiple_cursor.py”, line 28, in thread2_runtime
cursor.execute(sql)
File “/Users/lanyang/workspace/orange-service/.venv/lib/python3.6/site-packages/MySQLdb/cursors.py”, line 198, in execute
res = self._query(query)
File “/Users/lanyang/workspace/orange-service/.venv/lib/python3.6/site-packages/MySQLdb/cursors.py”, line 304, in _query
db.query(q)
File “/Users/lanyang/workspace/orange-service/.venv/lib/python3.6/site-packages/MySQLdb/connections.py”, line 217, in query
_mysql.connection.query(self, query)
MySQLdb._exceptions.ProgrammingError: (2014, “Commands out of sync; you can’t run this command now”)
thread name:thread 001, ret:(1,)
…main exit…
从打印结果可以看到,线程1可以正常打印结果,但线程2报错了。
线程1睡眠先结束,去获取查询结果,可以打印。
线程2睡眠后结束,再去获取查询结果,已经无法获取结果了。
2.总结
从上面例子中,我们可以得出结论:
一个连接connection同一个时间点只能有一个cursor,执行sql,并获取结果。
所以,不要在多个线程中同时使用一个连接connection,否则会出现不可预料的结果。
python MySQLdb 一个连接connection多个cursor相关推荐
- Python MySQLdb模块连接操作mysql数据库实例_python
mysql是一个优秀的开源数据库,它现在的应用非常的广泛,因此很有必要简单的介绍一下用python操作mysql数据库的方法.python操作数据库需要安装一个第三方的模块,在http://mysql ...
- php mysqldb 数据库切换,Python MySQLdb模块连接操作mysql数据库实例
mysql是一个优秀的开源数据库,它现在的应用非常的广泛,因此很有必要简单的介绍一下用python操作mysql数据库的方法.python操作数据库需要安装一个第三方的模块,在http://mysql ...
- 一个jdbc connection连接对应一个事务
Spring保证在methodB方法中所有的调用都获得到一个相同的连接.在调用methodB时,没有一个存在的事务,所以获得一个新的连接,开启了一个新的事务. Spring保证在methodB方法中所 ...
- 服务器关闭重启后客户端socket能自动连接吗_用Python 撸一个 Web 服务器
从一个 Hello World 程序说起 要编写 Web 服务器,需要用到一个 Python 内置库 socket.Socket 是一个比较抽象的概念,中文叫套接字,它代表一个网络连接.两台计算机之间 ...
- Python MySQLdb 学习总结
任何应用都离不开数据,所以在学习python的时候,当然也要学习一个如何用python操作数据库了.MySQLdb就是python对mysql数据库操作的模块.官方Introduction : MyS ...
- Python MySQLdb 模块使用方法
import MySQLdb 2.和数据库建立连接 conn=MySQLdb.connect(host="localhost",user="root",pas ...
- python写一个通讯录step by step V3.0
python写一个通讯录step by step V3.0 更新功能: 数据库进行数据存入和读取操作 字典配合函数调用实现switch功能 其他:函数.字典.模块调用 注意问题: 1.更优美的格式化输 ...
- python 使用pymssql连接sql server数据库
Python连接SQL Server数据库 - pymssql使用基础 ----原文地址:http://www.cnblogs.com/baiyangcao/p/pymssql_basic.html ...
- python sqlserver api连接池_非常老的话题 SQLSERVER连接池
非常老的话题 SQLSERVER连接池 写这篇文章不是说要炒冷饭,因为园子里有非常非常多关于SQLSERVER连接池的文章,但是他们说的都是引用MSDN里的解释 或者自己做一些测试试验一下连接池的性能 ...
- Python MySQLdb 循环插入execute与批量插入executemany性能分析(list批量写法亲测成功)
用Python连接MySQL数据库时,会用到MySQLdb库,这里下载↓↓↓ https://pypi.python.org/pypi/MySQL-python/ 这个库提供了对数据库的普遍操作,增删 ...
最新文章
- 谢尔盖.布林的早期思想_谷歌联合创始人谢尔盖·布林(Sergey Brin)谈人工智能与自动化...
- 开源数据库连接池之Tomcat内置连接池
- 全球及中国枕式自动包装机行业需求现状与投资机会评估报告2022-2027年版
- Redmine 数据库连接错误
- 学php5还是php7,学习猿地-php5.*与php7.* 区别
- POJ1003/1004/1005/1207/3299/2159/1083/3094/2388解题(刷一波水题)
- 那篇让汤普金斯进入梦境的相对论演讲
- API的 Signature(签名)Token(令牌) 认证
- prism v2之旅(7)
- 使用C#的后端Web API:循序渐进教程
- 机器学习库sklearn之怎么划分训练集和测试集
- Photoshop抠图--使用图层蒙版抠图
- 用html制作的旅游相册名字唯美,好听的相册名字
- 串口异步通信——时序宽度测试
- ORAN C平面 Section Extension 5
- MATLAB 错误使用 instfreq TFD 应“非负”
- jQuery学习教程
- 看雪2020CTF 守株待兔
- 2014年教育领域五大事件立业公信
- How much do you know in R language