- 論壇徽章:
- 0
|
執(zhí)行數(shù)據(jù)庫(kù)刪除,使用了django的cursor.execute(sql)進(jìn)行刪除數(shù)據(jù),發(fā)現(xiàn)了奇怪問(wèn)題,有時(shí)候可以執(zhí)行成功,有的時(shí)候執(zhí)行不成功。
通過(guò)SQL的監(jiān)控看到SQL語(yǔ)句是正常的,就是沒(méi)有執(zhí)行commit
代碼應(yīng)該是沒(méi)問(wèn)題的:
Python代碼
from django.db import connection cursor = connection.cursor() cursor.execute("delete from event where id=%s",[event_id]) cursor.close()
想不通問(wèn)題出在什么地方,有的地方用類似的代碼就可以,最后還是改成了django自己的那套刪除方法:
object.delete()
自己也封裝了個(gè)數(shù)據(jù)庫(kù)操作的類。
Python代碼
class Database: def get_connection(self): connection = Connection(host="localhost",user="root",passwd="",use_unicode=True,charset="utf8") connection.select_db(‘ppsea_main’) return connection def get_cursor(self): return self.get_connection().cursor() # 根據(jù)SQL取一條指定數(shù)據(jù) def select_fetchone(self,sql): cursor = self.get_cursor() cursor.execute(sql) print "select_fetchone sql: %s" %(sql) object = cursor.fetchone() desc = cursor.description if object: print object d = {} i = 0 for item in desc: d[item[0]] = object i=i+1 print "one %s" %(d) return d else: return object # 根據(jù)SQL取的數(shù)據(jù)列表 def select_fetchall(self,sql): cursor = self.get_cursor() cursor.execute(sql) print "select_fetchall sql: %s" %(sql) items = cursor.fetchall() desc = cursor.description li = [] if items: for item in items: d = {} i = 0 for de in desc: d[de[0]] = item i=i+1 li.append(d); return li else: return li # 執(zhí)行插入和更新 def execute(self,sql): print "execute sql : %s" %(sql) connection = self.get_connection() cursor=connection.cursor() cursor.execute(sql) connection.commit()
通過(guò)自己的方法調(diào)用也沒(méi)問(wèn)題,自己的理解應(yīng)該是django中使用cursor.execute執(zhí)行后沒(méi)有commit。
不知道是不是django的版本問(wèn)題,我用的是Django-1.0.2-final,遇到類似問(wèn)題的哥們可以一起討論討論。
更新:
經(jīng)過(guò)不斷嘗試,終于試出解決方法,在execute后加上cursor.execute("commit")
完整代碼:
Python代碼
from django.db import connection cursor = connection.cursor() cursor.execute("delete from event where id=%s",[event_id]) cursor.execute("commit") cursor.close()
本文來(lái)自ChinaUnix博客,如果查看原文請(qǐng)點(diǎn):http://blog.chinaunix.net/u2/84280/showart_2045759.html |
|