Python Django 之 直接执行自定义SQL语句(一)

一、执行自定义SQL方法

1、Executing custom SQL directly

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

2、Manager.raw()

执行原始查询并返回模型实例

二、Executing custom SQL directly

Manager.raw() 远远不够,可直接执行自定义SQL,directly execute UPDATE , INSERT , or DELETE queries.
django.db.connection:代表默认的数据库连接
django.db.transaction :代表默认数据库事务(transaction)
用database connection调用 connection.cursor() 得到一个游标(cursor)对象。
然后调用 cursor.execute(sql, [params]) 执行SQL
cursor.fetchone() 或者 cursor.fetchall(): 返回结果行
如果执行修改操作,则调用 transaction.commit_unless_managed()来保证你的更改提交到数据库。
def my_custom_sql():
    from django.db import connection, transaction
    cursor = connection.cursor()

# 数据修改操作——提交要求
    cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
    transaction.commit_unless_managed()

# 数据检索操作,不需要提交
    cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
    row = cursor.fetchone()

return row
  django.db.connections :针对使用多个数据库
from django.db import connections
cursor = connections[‘my_db_alias‘].cursor()
# Your code here...
transaction.commit_unless_managed(using=‘my_db_alias‘)
 通常我们不需要手动调用 transaction.commit_unless_managed( ),我们可以这样做:
@commit_on_success
def my_custom_sql_view(request, value):
    from django.db import connection, transaction
    cursor = connection.cursor()

# Data modifying operation
    cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [value])

# Since we modified data, mark the transaction as dirty
    transaction.set_dirty()

# Data retrieval operation. This doesn‘t dirty the transaction,
    # so no call to set_dirty() is required.
    cursor.execute("SELECT foo FROM bar WHERE baz = %s", [value])
    row = cursor.fetchone()

return render_to_response(‘template.html‘, {‘row‘: row})
查看Django ORM执行的SQL语句 :   connection.queries

三、raw()方法

1、raw()用法

The raw() manager method can be used to perform raw SQL queries that return model instances:
Manager. raw ( raw_query , params=None , translations=None )
用法:
 
>>> for p in Person.objects.raw(‘SELECT * FROM Person LIMIT 2‘):
...     print p
John Smith
Jane Jones
 注意,原始SQL里的model,如果在 db_table 没有定义,则使用app的名称,后面下划线 后面接模型类的名称,如"Myblog_New";上面的例子,在定义类的时候已经这样处理了:
Class New(models.Model):
    ......
    ......
#自定义表名
    class Meta:
        db_table = ‘New‘

2、查询字段隐射到模型字段(Mapping query fields to model fields)

raw() automatically maps fields in the query to fields on the model.并且是通过名称来匹配,这意味着我们可以使用SQL子句(clause)
>>> Person.objects.raw(‘‘‘SELECT first AS first_name,
...                              last AS last_name,
...                              bd AS birth_date,
...                              pk as id,
...                       FROM some_other_table‘‘‘)
 返回一个RawQuerySet对象

3、索引查找(Index lookups)

first_person = Person.objects.raw(‘SELECT * from myapp_person‘)[0]
first_person = Person.objects.raw(‘SELECT * from myapp_person LIMIT 1‘)[0]
#然而,索引和切片不是在数据库级别上执行(除LIMIT外)

4、延迟模型字段(Deferring model fields)

Fields may also be left out(left out:忽视,不考虑;被遗忘),这意味着该字段的查询将会被排除在根据需要时的加载。
>>> for p in Person.objects.raw(‘SELECT id, first_name FROM myapp_person‘):
...     print p.first_name, # 这将检索到原始查询
...     print p.last_name # 这将检索需求
...
John Smith
Jane Jones
 这个例子其实检索了三个字段,一个主键(必需)、一个原始SQL字段、一个需求字段。这里主键字段不能省略,否则会出错,如下:

5、传递参数(Passing parameters into raw() )

如果需要执行参数化查询,您可以使用params参数原始()

注意两点:

(1)、必须使用[参数],否则出错:
(2)、这种方式不对:
Error:
>>> query = ‘SELECT * FROM myapp_person WHERE last_name = %s‘ % lname
>>> Person.objects.raw(query)

转载自:https://www.cnblogs.com/hello-/articles/9095444.html

原文地址:https://www.cnblogs.com/xibuhaohao/p/10376474.html

时间: 2024-08-03 09:08:58

Python Django 之 直接执行自定义SQL语句(一)的相关文章

在django中,执行原始sql语句

extra()方法 结果集修改器,一种提供额外查询参数的机制 使用extra: 1:Book.objects.filter(publisher__name='广东人员出版社').extra(where=['price>50']) Book.objects.filter(publisher__name='广东人员出版社',price__gt=50) 2:Book.objects.extra(select={'count':'select count(*) from hello_Book'}) ra

Django 之 查看执行的sql语句

前提: 我的app名称为core,models.py内容如下: # coding:utf-8 from django.db import models # Create your models here. class Province(models.Model): name = models.CharField(u'省份名称',max_length=32) code = models.IntegerField(verbose_name=u'区号', unique=True) def __unic

django不定义model,直接执行自定义SQL

如果不想定义model,直接执行自定义SQL,可如下操作: 1. 通过 connections获取db连接,如果是多个数据库,connections['dbName'] 来选择 2. 获取游标 cursor 3. 执行sql: cursor.execute(sql) 4.获取返回结果:fetchone,fetchall (fetchall返回的是元祖,非字典) from django.db import connections cursor = connections['test_db'].cu

Python将JSON格式数据转换为SQL语句以便导入MySQL数据库

前文中我们把网络爬虫爬取的数据保存为JSON格式,但为了能够更方便地处理数据,我们希望把这些数据导入到MySQL数据库中.phpMyadmin可以把MySQL数据库中的数据导出为JSON格式文件,但却不能把JSON格式文件导入到MySQL数据库.为了实现这个目标,可以编写Python脚本将JSON格式数据转换为SQL语句以便导入MySQL数据库. JSON文件tencent.json部分内容: {"recruitNumber": "1", "name&qu

Sql Server 查看当前正在执行的Sql 语句

查看Sql Server 当前正在执行的Sql 语句,可以使用 sys.sysprocesses 或 sys.dm_exec_requests,由于sys.sysprocesses是为了向后兼容而保留的,所以,推荐使用DMV:sys.dm_exec_requests 一,使用sys.sysprocesses Contains information about processes that are running on an instance of SQL Server. These proce

LoadRunner 执行单句SQL语句

LoadRunner 执行单句SQL语句 Action() { int NumRows=0; int i=1; //建立数据库连接 lr_db_connect("StepName=DatabaseConnection", "ConnectionString=Provider=SQLOLEDB.1;Password=***;Persist Security Info=True;User ID=sc;Initial Catalog=EGMIS_NET;Data Source=19

[转]查询sqlserver 正在执行的sql语句的详细信息

包含用户名,所在数据库,执行的sql语句,执行开始时间,驱动程序,主机名称 SELECT     [Spid] = session_Id, ecid, [Database] = DB_NAME(sp.dbid), [User] = nt_username, [Status] = er.status, [Wait] = wait_type, [Individual Query] = SUBSTRING(qt.text, er.statement_start_offset / 2, (CASE WH

存储过程中执行动态Sql语句

存储过程中执行动态Sql语句 MSSQL为我们提供了两种动态执行SQL语句的命令,分别是EXEC和sp_executesql;通常,sp_executesql则更具有优势,它提供了输入输出接口,而EXEC没有.还有一个最大的好处就是利用sp_executesql,能够重用执行计划,这就大大提供了执行性能,还可以编写更安全的代码.EXEC在某些情况下会更灵活.除非您有令人信服的理由使用EXEC,否侧尽量使用sp_executesql. 1.EXEC的使用 EXEC命令有两种用法,一种是执行一个存储

EF-记录程序自动生成并执行的sql语句日志

在EntityFramework的CodeFirst模式中,我们想将程序自动生成的sql语句和执行过程记录到日志中,方便以后查看和分析. 在EF的6.x版本中,在DbContext中有一个Database属性,Database.Log就是用来专门记录这种日志的. Database.Log是一个Action<string>委托,给其赋值一个函数就行. 代码如下: using Model; using System; using System.Collections.Generic; using