python用mysqldb時查詢緩衝問題

2021-10-24 00:24:46 字數 2263 閱讀 3397

class dbbasehandle:

def __init__(self):

try:

self.conn = mysqldb.connect(host=syn_config.mysql_server.get('host'), user=syn_config.mysql_server.get('user'), passwd=syn_config.mysql_server.get('passwd'), db=syn_config.mysql_server.get('db'),charset=syn_config.mysql_server.get('charset'))

self.cursor = self.conn.cursor()

except exception,e:

logger.error('connect mysql error:%s'%e)

self.conn = mysqldb.connect(host=syn_config.mysql_server.get('host'), user=syn_config.mysql_server.get('user'), passwd=syn_config.mysql_server.get('passwd'), db=syn_config.mysql_server.get('db'),charset=syn_config.mysql_server.get('charset'))

self.cursor = self.conn.cursor()

def close(self):

self.conn.close()

self.cursor.close()

def rollback(self):

self.conn.rollback()

class dbhandle(dbbasehandle):

def get_all_follow(self,uid):try:

data =

self.cursor.execute("select uid2 from user_following where uid=%s;"%uid)

result = self.cursor.fetchall()

if result:

for res in result:

self.close()

return data

finally: ###新增了此處解決問題

self.conn.commit() ###新增了此處解決問題

class testhandle(dbbasehandle):

def test(self,uid,vuids):

try:

for vuid in vuids:

self.cursor.execute("insert into user_following(uid,uid2,follow_time) values(%s,%s,%s);"%(int(uid),int(vuid),int(time.time())))

return true

#except : 唯一性錯誤

except exception,e:

logger.error('uid:%s,create follow error:%s'%(uid,e))

print e

self.rollback()

return false

finally:

self.conn.commit()

if __name__ == "__main__":

logger.info("start test ******************")

d1 = dbhandle.get_all_follow(123)

testhandle().test(123,[1,2,3,4])

d2 = dbhandle.get_all_follow(123)

當**中沒有紅色部分時,執行**,d1與d2是一樣的,這兒就是mysqldb存在緩衝的問題

解決方法:

1、語句末尾加上「commit;」 

2 、執行完語句,至少在關閉資料庫之前提交一下,如:conn.commit()

3、資料庫連線建立之後,設定自動提交,如:conn.autocommit(1) 

mysql不同的儲存引擎對應的commit不同,所以要針對不同的儲存引擎開啟autocommit或關閉。mysqldb 在連線後關閉了自動提交,自動提交對於 innodb 引擎很重要,沒有這個設定,innodb 引擎就不會真正執行語句。 

參考:

安裝MySQLdb模組 python

mysqldb官網 安裝編譯 cd usr local src mysql python 1.2.4b4 python setup.py build python setup.py install 在執行python setup.py build時回報environmenterror mysql c...

Python基礎 MySQLdb模組

pip install mysqldb去除乙個資料庫中所有的表 import mysqldb def db test conn mysqldb.connect user passwd db charset utf8 cursor conn.cursor cursor.execute show tab...

python下的MySQLdb使用

1.引入mysqldb庫 import mysqldb 2.和資料庫建立連線 conn mysqldb.connect host localhost user root passwd sa db mytable charset utf8 提供的connect方法用來和資料庫建立連線,接收數個引數,返...