Django执行原生SQL语句的方法
1、extra
结果集修改器,一种提供额外查询参数的机制
extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None)
select和select_params是一组,where和params是一组,tables用来设置from哪个表
下面举例说明:
#查找userinfo表中的所有内容
import user #导入user这个模块
res1=user.models.UserInfo.objects.extra(table=['userinfo'])
for a in res1:
print(a.name,a.age,a.phone)
以上语句相当于:
select * from userinfo;
2、row
执行原始SQL返回模型实例
同样以查找userinfo表中的所有内容为例:
import user
def a1(request):
res2=user.models.UserInfo.objects.raw('select * from user_userinfo')
for a in res2:
print(a.name,a.age,a.phone)
return render(request,'search.html')
3、connection/connections
直接执行自定义SQL(此方法不依赖model)
from django.db import connection,connections
cursor = connection.cursor()
# cursor = connections['default'].cursor()
def a1(request):
aa = cursor.execute("select * from user_userinfo")
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print(aa)
# row = cursor.fetchone() #返回结果行游标直读向前,读取一条
row1=cursor.fetchall() # 读取所有
print(row1)
return render(request,'search.html')
4、sqlalchemy
首先导入sqlalchemy的包
from django.db import sqlalchemy
下面以代码示例:
def text(request):
from sqlalchemy import create_engine
#engine = create_engine("mysql://scott:tiger@hostname/dbname",
#encoding='latin1', echo=True)
engine=create_engine('mysql://root:mysql@localhost/pai0806')
cur=engine.execute("select * from user_userinfo")
print(cur)
for obj in cur.fetchall():
print(obj)
return HttpResponse('ok')