方式1
包含主键
for d in Stu.objects.raw('select * from t_stu'):
print d
Stu:zhangsan,88
Stu:lisi,90
Stu:wangwu,99
Stu:zhangjie,66
Stu:xiena,89
不包含主键
for d in Stu.objects.raw('select sname,score from t_stu'):
print d
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\Python27\lib\site-packages\django\db\models\query.py", line 1245, in __iter__
raise InvalidQuery('Raw query must include the primary key')
InvalidQuery: Raw query must include the primary key
方式2
包含主键
from student.models import *
from django.db import connection
cursor = connection .cursor()
cursor.execute('select * from t_stu')
5L
datas = cursor.fetchall()
print datas
((1L, u'zhangsan', 88L, datetime.date(2018, 4, 7), 1L), (2L, u'lisi', 90L, datetime.date(2018, 4, 7), 2L), (3L, u'wangwu', 99L, datetime.date(2018, 4, 7), 3L), (4L, u'zhangjie', 66L, datetime.date(2018, 4, 7), 1L), (5L, u'xiena', 89L, datetime.date(2018, 4, 7), 3L))
for d in datas:
print d
(1L, u'zhangsan', 88L, datetime.date(2018, 4, 7), 1L)
(2L, u'lisi', 90L, datetime.date(2018, 4, 7), 2L)
(3L, u'wangwu', 99L, datetime.date(2018, 4, 7), 3L)
(4L, u'zhangjie', 66L, datetime.date(2018, 4, 7), 1L)
(5L, u'xiena', 89L, datetime.date(2018, 4, 7), 3L)
cursor.close()
不包含主键
from student.models import *
from django.db import connection
cursor= connection.cursor()
cursor.execute('select sname,score from t_stu')
5L
ds = cursor.fetchall()
print ds
((u'zhangsan', 88L), (u'lisi', 90L), (u'wangwu', 99L), (u'zhangjie', 66L), (u'xiena', 89L))
cursor.close()
获取一条记录
from student.models import *
from django.db import connection
cursor= connection.cursor()
cursor.execute('select * from t_stu where sno=1')
1L
cursor.fetchone()
(1L, u'zhangsan', 88L, datetime.date(2018, 4, 7), 1L)
cursor.close()
MySQL外连接
SQL92:select * from ltable,rtable where ltable.column=rtable.column(+)
SQL99: select * from ltable left join rtable on (ltable.column=rtable.column)