=Start=
缘由:
简单记录一下前段时间碰到的小问题的解决记录,方便以后参考。
正文:
参考解答:
对于一个不是很繁忙的(存在数据库连接的)后台服务来说,可能存在数据库连接自动断开的情况,因为数据库默认的 wait_timeout=28800 ,单位是秒,换算后是8小时,也就是你的服务启动8小时后,如果这期间没有任何SQL操作,就会被MySQL自动断开。如果没有自动检测重连机制,服务可能就不可用了。
如果你选用的ORM框架会做连接保活处理也还OK,就不需要考虑这个问题(但是你也要了解有这个问题,只不过是框架帮你处理了)。
如果你选择的是MySQLdb/pymysql这样的库,就需要自己处理这个问题:
· StackOverflow上的回答是建议不要使用全局游标,而是每次使用的时候动态创建连接,使用了之后再主动销毁;
· 另外一个办法就是使用全局游标,但是每次实际SQL操作之前,先用ping检查一下连接状态,不行的了话再新建一个。
如果你的后台服务比较繁忙,那最好还是用现成的数据库连接池工具来处理,性能和稳定性都会比上面这两种手工的方法更好。
&
import pymysql
class MySQL(object):
def __init__(self, host='127.0.0.1', port=3306, user='', passwd='', db='', charset=''):
self.host = host
self.port = port
self.user = user
self.passwd = passwd
self.db = db
self.charset = charset
self.conn = None
self.cur = None
self.__connect()
def __connect(self):
try:
self.conn = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db, charset=self.charset)
self.cur = self.conn.cursor()
except pymysql.MySQLError as e:
print( 'Error Message: {}'.format(e) )
def conn_test(self):
try:
print( 'conn_test ping()' )
self.conn.ping(reconnect=True)
except pymysql.MySQLError as e:
print( 'Error Message: {}'.format(e) )
self.__connect()
def safe_query(self, mode, param_tuple):
self.conn_test()
ret_tuple = None
try:
self.cur.execute(mode, param_tuple)
ret_tuple = self.cur.fetchall()
self.conn.commit()
except pymysql.MySQLError as e:
print( 'Error Message: {}'.format(e) )
return ret_tuple
def safe_update(self, mode, param_tuple):
self.conn_test()
try:
self.cur.execute(mode, param_tuple)
self.conn.commit()
except pymysql.MySQLError as e:
self.conn.rollback()
print( 'Error Message: {}'.format(e) )
def close(self):
self.cur.close()
self.conn.close()
self.cur = None
self.conn = None
mysql = MySQL(host='127.0.0.1', port=3306, user='user_name', passwd='user_pass', db='db_name', charset='utf8mb4')
参考链接:
- InterfaceError (0, ”)
https://stackoverflow.com/questions/6650940/interfaceerror-0 - Python MySQLdb模块中的ping()
https://www.cnblogs.com/bugmaker/articles/2444905.html - 【Python】数据库异常pymysql.err.InterfaceError: (0, ”)解决方案
https://blog.csdn.net/u013948858/article/details/88343426 - 解决 MySQLdb 的数据库连接超时问题
https://lightless.me/archives/mysqldb-lost-connection-to-mysql.html
=END=
《“解决Python数据库连接超时问题”》 有 1 条评论
How to use python mysqldb to insert many rows at once
https://stackoverflow.com/questions/14011160/how-to-use-python-mysqldb-to-insert-many-rows-at-once
`
n = cursor.executemany(sql, param)
cursor.executemany(
“””INSERT INTO breakfast (name, spam, eggs, sausage, price)
VALUES (%s, %s, %s, %s, %s)”””,
[ (“Spam and Sausage Lover’s Plate”, 5, 1, 8, 7.95 ),
(“Not So Much Spam Plate”, 3, 2, 0, 3.95 ),
(“Don’t Wany ANY SPAM! Plate”, 0, 4, 3, 5.95 ) ]
)
`
http://mysql-python.sourceforge.net/MySQLdb.html
https://pynative.com/python-mysql-insert-data-into-database-table/
Python MySQLdb 循环插入execute与批量插入executemany性能分析
https://blog.csdn.net/colourless/article/details/41444069