django 中执行原生sql的方法


一共有三种方法:

1.extra函数

详情见:https://www.cnblogs.com/sticker0726/p/8424453.html

 

2. raw(函数)

ret = Book.objects.raw('select * from hello_Book') # 返回queryset
for i in ret:
    print(i.id, i.name)

 

 

3.自定义SQL

直接执行自定义SQL

有时候raw()方法并不十分好用,很多情况下我们不需要将查询结果映射成模型,或者我们需要执行DELETE、 INSERT以及UPDATE操作。在这些情况下,我们可以直接访问数据库,完全避开模型层。

我们可以直接从django提供的接口中获取数据库连接,然后像使用pymysql模块一样操作数据库。

from django.db import connection, connections
cursor = connection.cursor()  # cursor = connections['default'].cursor()
cursor.execute("""SELECT * from auth_user where id = %s""", [1])
ret = cursor.fetchone()
from django.db import connection

cursor=connection.cursor()

# 插入操作
cursor.execute("insert into hello_author(name) values('钱钟书')")

# 更新操作
cursor.execute("update hello_author set name='abc' where name='bcd'")

# 删除操作
cursor.execute("delete from hello_author where name='abc'")

# 查询操作
cursor.execute("select * from hello_author")

raw=cursor.fetchone()  # 返回结果行游标直读向前,读取一条
cursor.fetchall()  # 读取所有


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM