码迷,mamicode.com
首页 > 数据库 > 详细

Django中sql与DB的交互——非ORM

时间:2017-08-21 11:25:47      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:select   user   res   content   title   article   htm   ima   return   

In your views.py,you can code like this :

 1 import MySQLdb
 2 def index(request):
 3     conn=MySqldb.connect(
 4         host=‘127.0.0.1‘,
 5         port=3306,
 6         user=‘root‘,
 7         passwd=‘root‘,
 8         db=‘pythonweb‘,
 9         charset=‘utf8‘,     #须与建立数据库时编码一致
10 
11         )
12     cursor=conn.cursor()   #定义游标
13     cursor.execute("SELECT * FROM firstapp_article")
14     results=cursor.fetchmany()
15 
16     articles=[]
17     for result in  results:
18         articles.append(
19             {
20                 # 这里与数据库中定义的表相匹配关联
21                 #result[0]为id
22                 ‘title‘:result[1],
23                 ‘content‘:result[2],
24                 ‘views‘:result[3],
25                 ‘likes‘:result[4],
26                 ‘createtime‘:result[5],
27                 ‘editors_choice‘:result[6],
28                 ‘cover‘:result[7],
29                 ‘url_image‘:result[8],
30             }
31 
32         )
33         context={}
34         context[‘articles‘]=articles
35     return render(request,‘index.html‘,context)            

 

Django中sql与DB的交互——非ORM

标签:select   user   res   content   title   article   htm   ima   return   

原文地址:http://www.cnblogs.com/reaptem/p/7403235.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!