Django运行SQL语句

1、Manager.``raw(raw_queryparams=Nonetranslations=None)

1>>> for p in Person.objects.raw('SELECT * FROM myapp_person'): 2... print(p) 3John Smith 4Jane Jones

这个方法接受一个原始的SQL查询,执行它,并返回一个django.db.models.query。RawQuerySet实例。这个RawQuerySet实例可以像普通的QuerySet一样遍历,以提供对象实例。

(1)字段匹配

1>>> Person.objects.raw('''SELECT first AS first_name, 2... last AS last_name, 3... bd AS birth_date, 4... pk AS id, 5... FROM some_other_table''') 6 7 8>>> name_map = {'first': 'first_name', 'last': 'last_name', 'bd': 'birth_date', 'pk': 'id'} 9>>> Person.objects.raw('SELECT * FROM some_other_table', translations=name_map)

(2)即使没有显示表明查询字段,也可以获取

1>>> for p in Person.objects.raw('SELECT id, first_name FROM myapp_person'): 2... print(p.first_name, # This will be retrieved by the original query 3... p.last_name) # This will be retrieved on demand 4... 5John Smith 6Jane Jones

(3)执行带参数SQL

字符串用%s占位符

字典用%(key)s占位符

1>>> lname = 'Doe' 2>>> Person.objects.raw('SELECT * FROM myapp_person WHERE last_name = %s', [lname])

(4)严禁使用字符串拼接

1>>> query = 'SELECT * FROM myapp_person WHERE last_name = %s' % lname 2>>> Person.objects.raw(query)

(4)参数不能用引号包裹

>>> query = "SELECT * FROM myapp_person WHERE last_name = '%s'"

2、通过connection.cursor()执行SQL

对象django.db.connection表示默认的数据库连接。要使用数据库连接,请调用connection.cursor()来获得一个游标对象。然后调用cursor.execute(sql, [params])方法以执行sql

cursor.fetchone()或cursor.fetchall()以返回结果行。

1from django.db import connection 2 3def my_custom_sql(self): 4 with connection.cursor() as cursor: 5 cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz]) 6 cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz]) 7 row = cursor.fetchone() 8 9 return row

(1)传递百分比参数需要写两个百分号

cursor.execute("SELECT foo FROM bar WHERE baz = '30%%' AND id = %s", [self.id])

(2)cursor执行不会返回列名

用字典或命名元组

1def dictfetchall(cursor): "Return all rows from a cursor as a dict" columns = [col[0] for col in cursor.description] return [ dict(zip(columns, row)) for row in cursor.fetchall() ] 2 3from collections import namedtuple 4 5def namedtuplefetchall(cursor): "Return all rows from a cursor as a namedtuple" desc = cursor.description nt_result = namedtuple('Result', [col[0] for col in desc]) return [nt_result(*row) for row in cursor.fetchall()] 6 7>>> cursor.execute("SELECT id, parent_id FROM test LIMIT 2"); 8>>> dictfetchall(cursor) 9[{'parent_id': None, 'id': 54360982}, {'parent_id': None, 'id': 54360880}]
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )

Django运行SQL语句 - HelloWorld