Chinaunix
标题:
django中使用cursor.execute更新数据库问题?
[打印本页]
作者:
hkebao
时间:
2009-09-04 19:13
标题:
django中使用cursor.execute更新数据库问题?
执行数据库删除,使用了django的cursor.execute(sql)进行删除数据,发现了奇怪问题,有时候可以执行成功,有的时候执行不成功。
通过SQL的监控看到SQL语句是正常的,就是没有执行commit
代码应该是没问题的:
Python代码
from django.db import connection
cursor = connection.cursor() cursor.execute("delete from event where id=%s",[event_id])
cursor.close()
想不通问题出在什么地方,有的地方用类似的代码就可以,最后还是改成了django自己的那套删除方法:
object.delete()
自己也封装了个数据库操作的类。
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()
# 根据SQL取一条指定数据
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
# 根据SQL取的数据列表 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
# 执行插入和更新 def execute(self,sql):
print "execute sql : %s" %(sql) connection = self.get_connection()
cursor=connection.cursor() cursor.execute(sql)
connection.commit()
通过自己的方法调用也没问题,自己的理解应该是django中使用cursor.execute执行后没有commit。
不知道是不是django的版本问题,我用的是Django-1.0.2-final,遇到类似问题的哥们可以一起讨论讨论。
更新:
经过不断尝试,终于试出解决方法,在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()
本文来自ChinaUnix博客,如果查看原文请点:
http://blog.chinaunix.net/u2/84280/showart_2045759.html
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2