python mysql数据库长连接_python 长连接 mysql数据库
python 長連接數據庫
python鏈接mysql中沒有長鏈接的概念,但我們可以利用mysql的ping機制,來實現長鏈接功能
思路:
1 python mysql 的cping 函數會校驗鏈接的可用性,如果連接不可用將會產生異常
2 利用這一特性,構造一個連接丟失的循環,不斷嘗試連接數據庫,直到連接恢復
3 使用這樣的機制不需要關閉數據庫功能,對于駐留進程,有大量數據進行寫操作時,很有用途#!/usr/bin/env?python
#?-*-coding:UTF-8-*-
import?MySQLdb
class?mysql:
def?__init__?(self,
host???=?'',
user???=?'',
passwd?=?'',
db?????=?'',
port???=?3306,
charset=?'utf8'
):
self.host???=?host
self.user???=?user
self.passwd?=?passwd
self.db?????=?db
self.port???=?port
self.charset=?charset
self.conn???=?None
self._conn()
def?_conn?(self):
try:
self.conn?=?MySQLdb.Connection(self.host,?self.user,?self.passwd,?self.db,?self.port?,?self.charset)
return?True
except?:
return?False
def?_reConn?(self,num?=?28800,stime?=?3):?#重試連接總次數為1天,這里根據實際情況自己設置,如果服務器宕機1天都沒發現就......
_number?=?0
_status?=?True
while?_status?and?_number?<=?num:
try:
self.conn.ping()???????#cping?校驗連接是否異常
_status?=?False
except:
if?self._conn()==True:?#重新連接,成功退出
_status?=?False
break
_number?+=1
time.sleep(stime)??????#連接不成功,休眠3秒鐘,繼續循環,知道成功或重試次數結束
def?select?(self,?sql?=?''):
try:
self._reConn()
self.cursor?=?self.conn.cursor(MySQLdb.cursors.DictCursor)
self.cursor.execute?(sql)
result?=?self.cursor.fetchall()
self.cursor.close?()
return?result
except?MySQLdb.Error,e:
#print?"Error?%d:?%s"?%?(e.args[0],?e.args[1])
return?False
def?handle?(self,?sql?=?''):
try:
self._reConn()
self.cursor?=?self.conn.cursor(MySQLdb.cursors.DictCursor)
self.cursor.execute?("set?names?utf8")?#utf8?字符集
self.cursor.execute?(sql)
self.conn.commit()
self.cursor.close?()
return?True
except?MySQLdb.Error,?e:
print?"Error?%d:?%s"?%?(e.args[0],?e.args[1])
return?False
def?close?(self):
self.conn.close()
if?__name__=='__main__':
my?=?mysql('localhost','user','passwd','test',3306)
my.handle('create?table?test(id?int,name?varchar(10))default?charset=utf8')
my.handle('insert?into?test?values(1,"tom")')
print?my.select('select?*?from?test')
#my.close()
總結
以上是生活随笔為你收集整理的python mysql数据库长连接_python 长连接 mysql数据库的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: spark python3.6_在mac
- 下一篇: python经典排序_python实现十