日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

python 长连接 mysql数据库

發(fā)布時(shí)間:2025/3/19 数据库 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python 长连接 mysql数据库 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.


python 長(zhǎng)連接數(shù)據(jù)庫(kù)

python鏈接mysql中沒有長(zhǎng)鏈接的概念,但我們可以利用mysql的ping機(jī)制,來實(shí)現(xiàn)長(zhǎng)鏈接功能


思路:

1 python mysql 的cping 函數(shù)會(huì)校驗(yàn)鏈接的可用性,如果連接不可用將會(huì)產(chǎn)生異常

2 利用這一特性,構(gòu)造一個(gè)連接丟失的循環(huán),不斷嘗試連接數(shù)據(jù)庫(kù),直到連接恢復(fù)

3 使用這樣的機(jī)制不需要關(guān)閉數(shù)據(jù)庫(kù)功能,對(duì)于駐留進(jìn)程,有大量數(shù)據(jù)進(jìn)行寫操作時(shí),很有用途

#!/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):?#重試連接總次數(shù)為1天,這里根據(jù)實(shí)際情況自己設(shè)置,如果服務(wù)器宕機(jī)1天都沒發(fā)現(xiàn)就......??_number?=?0??_status?=?True??while?_status?and?_number?<=?num:??try:??self.conn.ping()???????#cping?校驗(yàn)連接是否異常??_status?=?False??except:??if?self._conn()==True:?#重新連接,成功退出??_status?=?False??break??_number?+=1??time.sleep(stime)??????#連接不成功,休眠3秒鐘,繼續(xù)循環(huán),知道成功或重試次數(shù)結(jié)束??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?Falsedef?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()


轉(zhuǎn)載于:https://blog.51cto.com/13558754/2090146

總結(jié)

以上是生活随笔為你收集整理的python 长连接 mysql数据库的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。