执行源生sql在python中我们可以借助pymysql模块来进行执行源生sql关于pymysql执行源生sql可以看我的另外一篇博文:pymysql应用

本篇博客只介绍django中执行的源生sql

1.使用extra方法

  解释:结果集修改器,一种提供额外查询参数的机制

  说明:依赖model模型

使用方式:

  用在where后:

    Book.objects.filter(publisher_id="").extra(where=["title='python学习1'"])    

  用在select后  

    Book.objects.filter(publisher_id="").extra(select={"count":"select count(*) from hello_book"})

2.使用raw方法

  解释:执行原始sql并返回模型

  说明:依赖model多用于查询

使用方式:

book = Book.objects.raw("select * from hello_book") #返回模型实例
    for item in book:
      print(item.title)

3.执行自定义SQL

  解释:利用游标执行

  导入:from django.db import connection

  说明:不依赖model

使用方式:

from django.db import connection

cursor = connection.cursor()
# 插入
cursor.execute("insert into hello_author(name) values('xiaol')")
# 更新
cursor.execute("update hello_author set name='xiaol' where id=1")
# 删除
cursor.execute("delete from hello_author where name='xiaol'")
# 查询
cursor.execute("select * from hello_author")
# 返回一行
raw = cursor.fetchone()
print(raw)
# 返回所有
# cursor.fetchall() 

最新文章

  1. jdk安装和环境变量配置
  2. 20161007 NOIP 模拟赛 T1 解题报告
  3. linux find 命令详解
  4. Redis 设计与实现读书笔记一 Redis List
  5. android:id="@+id/button1" 与 android:id="@id/button1" 区别 @string
  6. 【转】group by多个字段理解
  7. Js获取当前日期时间及其它操作(转)
  8. arcmap+vs2010
  9. Windows 2008 R2系统开机时如何不让Windows进行磁盘检测?
  10. Java条形码生成方案及二维码要点
  11. poj 2367 Genealogical tree【拓扑排序输出可行解】
  12. Byte[]、Image、Bitmap_之间的相互转换
  13. Asp.net中实现同一用户名同时登陆,注销先前用户(转)
  14. JS正则表达式之特殊符号
  15. Redis学习——Redis持久化之AOF备份方式保存数据
  16. Js相关用法个人总结
  17. activiti官网实例项目activiti-explorer实操详情
  18. 洛谷.3254.圆桌问题(最大流ISAP)
  19. es6 初级之let
  20. Tomcat安全管理规范

热门文章

  1. react-router刷新页面Cannot GET 问题
  2. c++ 拷贝构造函数(重点在内含指针的浅拷贝和深拷贝)
  3. ABP入门教程0 - 目录
  4. apache commons lang架包介绍
  5. C#&.Net干货分享- 构建Spire-Office相关Helper操作Word、Excel、PDF等
  6. django 做 migrate 时 表已存在的处理
  7. TYUT程序设计入门第四讲练习题题解--数论入门
  8. Unity ugui屏幕适配与世界坐标到ugui屏幕坐标的转换
  9. Vue 从入门到进阶之路(十三)
  10. Sql sever DateDiff 函数