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