dinggela 发表于 2017-5-5 06:42:26

python用mysqldb时查询缓冲问题

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:
data.append(res)
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,)
d2 = DBHandle.get_all_follow(123)
   

当代码中没有红色部分时,执行代码,d1与d2是一样的,这儿就是mysqldb存在缓冲的问题
解决方法:
1、语句末尾加上“COMMIT;” 
2 、运行完语句,至少在关闭数据库之前提交一下,如:conn.commit()
3、数据库连接建立之后,设置自动提交,如:conn.autocommit(1) 
 
mysql不同的存储引擎 对应的commit不同,所以要针对不同的存储引擎打开autocommit或关闭。MySQLdb 在连接后关闭了自动提交,自动提交对于 innodb 引擎很重要,没有这个设置,innodb 引擎就不会真正执行语句。 
 
 
参考:http://www.cnblogs.com/coser/archive/2012/01/12/2320741.html
 
 
 
页: [1]
查看完整版本: python用mysqldb时查询缓冲问题