django执行sql的三种方法 + pymysql +

1 执行原生sql

from dajngo from django.db import connection,connections

cursor = connection.cursor()
# cursor = connections['数据库的名字,setting设置的'].cursor()
cursor.execute("select * from app01_student")
row = cursor.fetchall()   # fetchone
print(row)

注意:

  • 默认情况下返回的是((xx,xx),(xx,xx)格式
  • 查询中如果有%,要用两个%%转义
  • 如果想返回字典形式(牺牲部分行能) 可如下
def  dictfetchall(cursor):
    desc = cursor.description
    # 相当于拿到表的字段
    return [
        dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()
    ]

row1 = dictfetchall(cursor)
print(row1)

[{'id': 1, 'username': '陈日天', 'age': 18, 'sex': 1, 'cs_id': 1}, {'id': 3, 'username': '斋藤飞鸟', 'age': 18, 'sex': 0, 'cs_id': 2}]
#   和上面的row不能并存

2偏原生

Entry.objects.extra(select={'new_id': "select col from sometable where othercol > %s"}, select_params=(1,))

Entry.objects.extra(where=["foo='a' OR bar = 'a'", "baz = 'a'"])

Entry.objects.extra(select={'new_id': "select id from tb where id > %s"}, select_params=(1,), order_by=['-nid'])


h = models.Teacher.objects.extra(select={'nname': 'select name from app01_teacher where id = %s'}, select_params=(3,))
print(h.first().nname)

3raw

 kk = models.Teacher.objects.raw('select * from app01_teacher where id = %s', params=[1,])
    for i in kk:
        print(i.name)



name_map = {'first': 'first_name', 'last': 'last_name', 'bd': 'birth_date', 'pk': 'id'}
Person.objects.raw('SELECT * FROM some_other_table', translations=name_map)
# 加参数  相当于 select first as first_name, last as last_name……

 

ps : 选择数据库时

queryset = models.Course.objects.using('default').all()

pymysql 

import pymysql

coon = pymysql.connect(host="localhost", port=3306, user='root', password='admin', database='wo')
a = "class"
cursor = coon.cursor(cursor=pymysql.cursors.DictCursor)     # 返回列表里面套字典,默认元组套元组
cursor.execute('select * from %s' % (a,))   # 加参数
data = cursor.fetchall()    # fetchone
print(data)
cursor.close()
coon.close()

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(django,db)