今天在寫python操作mysql的時候,出現了一個奇怪的現象,在用python代碼執行update的時候,代碼返回已經更新成功,但是數據庫表里的字段的值卻沒有改變,一直沒有找到錯誤的原因,結果尋求身邊同事的幫助,問題解決,在此做個記錄;
MysqlHelper.py 代碼如下
#! /usr/bin/python
# -*- coding: utf-8 -*-
HOST = '127.0.0.1'
PORT = 3306
USER = 'test'
PASSWORD = 'test123'
DBNAME = 'test'
CHARSET = 'utf8'
def connect():
try:
import MySQLdb
except ImportError, e:
#print e
return None
try:
cxn = MySQLdb.connect(host=HOST, user=USER, passwd=PASSWORD,port=PORT,db=DBNAME,charset=CHARSET)
#print cxn
return cxn
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
# 插入操作
def insert_one(cur,sql,value):
res = cur.execute(sql ,value)
# 插入成功,res 返回值為1
if 1 != res :
print 'failed'
else:
print 'success'
def insert_many(cur,sql,values):
res = cur.executemany(sql ,values)
# 插入成功,res 返回值為1
if 1 != res :
print 'failed'
else:
print 'success'
getRC = lambda cur: cur.rowcount if hasattr(cur,'rowcount') else -1
# 更新操作
def update(cur,sql,params):
cur.execute(sql , params)
return getRC(cur)
# 刪除操作
def delete(cur,sql,params):
cur.execute(sql,params)
return getRC(cur)
# 只獲取一條記錄,返回的是一個元組
def fetch_one(cur,sql):
count = cur.execute(sql)
#print count
result = cur.fetchone();
return result
# 獲取多條數據;返回的是二維元組;
def fetch_all(cur,sql):
count = cur.execute(sql)
#print count
results = cur.fetchall();
'''
print results
for r in results:
print r
'''
return results
# 提交的完成操作
def finish(cxn):
cxn.commit()
cxn.close()
我在其它的文件中調用
a.py
import MysqlHelper# 獲取數據庫各個表的主鍵 def getTablePrimaryKey(tablename): cxn = MysqlHelper.connect() cur = cxn.cursor() res = MysqlHelper.update(cur,"UPDATE table_primary_index "+ "SET index_primary_value=index_primary_value+1"+ " WHERE index_table_name =%s" , (tablename)) print res result = MysqlHelper.fetch_one(cur,"SELECT * FROM table_primary_index WHERE index_table_name='%s'" % tablename) print result
現象: print res 可以正確返回1,說明更新數據庫成功;
print result 也可以取到剛剛更新的值;
但是數據庫表中的值沒有變更;
原因:
python 操作mysql 是用 事物的方式來實現的,所以在update 的時候 必須有commit 提交的過程,否則數據表不會生效;
修改后的代碼如下:
b.py
# 獲取數據庫各個表的主鍵 def getTablePrimaryKey(tablename): cxn = MysqlHelper.connect() cur = cxn.cursor() res = MysqlHelper.update(cur,"UPDATE table_primary_index "+ "SET index_primary_value=index_primary_value+1"+ " WHERE index_table_name =%s" , (tablename)) print res result = MysqlHelper.fetch_one(cur,"SELECT * FROM table_primary_index WHERE index_table_name='%s'" % tablename) print result MysqlHelper.finish(cxn) return result[1]
