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

1-在mysql中建立的数据库,命名为:pythonweb

2-In your settings.py,set your database

 1 DATABASES = {
 2     'default': {     
 3          'ENGINE': 'django.db.backends.mysql',
 4         'NAME': 'pythonweb',
 5         'HOST': '127.0.0.1',
 6         'PORT': 3306,
 7          'USER': 'root',
 8         'PASSWORD': 'root',
 9     }
10 }

3-安装mysql引擎 

由于python默认并不自带mysql引擎,windows需要安装Mysqlclient(MAC可直接 pip install mysqlclient ),否则报错MySQLdb不存在

安装时注意与Python的版本号,位数(32、64)一致

Mysqlclient:http://www.lfd.uci.edu/~gohlke/pythonlibs/,

下载对应的版本的.whl文件后,pip install 安装即可

 

4-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)            

 5-In your templates,

1 {% for v in articles %}
2 <--#注意上面articel后面没有.all-->
3 {{v.title}}
4 {% endfor %}

 

转载于:https://www.cnblogs.com/reaptem/p/7403235.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值