1.说明
Django有自带的ORM框架,关于ORM的使用方法可以参考之前的文章
【Django】ORM模型类对数据库的增删改查、QuerySet查询集
但有时候我们需要执行原生的sql语句,Django也提供了相关的数据库连接
2.使用
from django.db import connection
cursor = connection.cursor()
try:
cursor.execute(...)
finally:
cursor.close()
connection.close()
from django.db import connection
with connection.cursor() as cursor:
effect_nums = cursor.execute("UPDATE student SET age=18 WHERE id =5")
cursor.execute("SELECT * FROM student WHERE age > 18")
row = cursor.fetchone()
3.不同数据库
如果你的项目有多个数据库,可以通过alias指定要连接哪个数据库。alias就是配置文件里DATABASES配置项的key。
例如我这里连接wallet3这个库
from django.db.utils import ConnectionHandler
from django.utils.connection import ConnectionProxy
def query_sql(sql):
connections = ConnectionHandler()
connection = ConnectionProxy(connections, "wallet3")
cursor = connection.cursor()
try:
cursor.execute(sql)
data = cursor.fetchall()
print("data:", data)
finally:
cursor.close()
connection.close()
return True, None