Django当中的sql查询

十二:在Django中使用sql
 
关键字:
connection     connections       transaction
insert/create/update/delete/select/drop
 
如果在models没有定义数据表名,将以app名加下划线加上定义的表名(自动转化为小写)
 
查询时可以直接使用raws函数进行sql查询
 
comment = Comment.objects.raw(select * from blog_comment)
 

Django提供两种方式执行(performing)原始的SQL查询:

(1)Manager.raw():执行原始查询并返回模型实例

(2)Executing custom SQL directly:直接执行自定义SQL,这种方式可以完全避免数据模型,而是直接执行原始的SQL语句。

raw() 方法自动通过查询字段映射到 model字段,并且是通过名称来匹配,这意味着我们可以使用SQL子句(clause)

注意当输入查询字段的时候,不要漏了主键(id),否则会出错

 

导入 form django.db import connection,transaction

django.db.connection:代表默认的数据库连接
django.db.transaction:代表默认数据库事务(transaction)
connection.cursor(): 获得一个游标(cursor)对象
cursor.execute(sql, [params]):执行SQL
cursor.fetchone() 或者 cursor.fetchall():返回结果行

如果执行修改操作,则调用transaction.commit_unless_managed()来保证你的更改提交到数据库。


 
def sql(request):
"""
----------------------------------------------
Function: 执行原始的SQL
DateTime: 2013/x/xx
----------------------------------------------
"""
from django.db import connection,transaction
cursor = connection.cursor()#获得一个游标(cursor)对象
#更新操作
cursor.execute('update other_other2 set name ="李四" where id=%s',[3])#执行sql语句
transaction.commit_unless_managed()#提交到数据库
#查询操作
cursor.execute('select * from other_other2 where id>%s',[1])
raw = cursor.fetchone()#返回结果行 或使用 #raw = cursor.fetchall()
 
#如果连接多个数据库则使用django.db.connections
from django.db import connections
_cursor = connections['other_database'].cursor()
#如果执行了更新、删除等操作
transaction.commit_unless_managed(using='other_databases')
return render_to_response('other/sql.html',{'raw':raw})
 





原文地址:https://www.cnblogs.com/wuqingzangyue/p/5749451.html