快乐学习Django&MySQL
注:刚开始学Python,很多东西都不懂,参考了很多博主的博客,记录下来以防自己忘记。若是有错误的地方,欢迎大家指正,谢谢。
1.读取数据库中的内容
1.首先创建数据库,数据库名称为person,创建student表如下所示。
插入部分测试数据
2.修改settings.py文件,找到DATABASES并进行如下修改:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'person', # 数据库名
'HOST': 'localhost', # 数据库主机
'PORT': 3306, # 数据库端口
'USER': 'root', # 数据库用户名
'PASSWORD': '123456', # 数据库用户密码
}
}
3.在templates目录下创建’list.html’文件,用于展示数据库中得到的数据。此时不需要对其进行修改。
4.在views.py中添加如下内容
from django.db import connection
def lists(request):
mycursor = connection.cursor();
mycursor.execute('select * from student')
rows = mycursor.fetchall()
for row in rows:
print(row)
return render(request,'list.html')
将读取到的数据首先在打印台输出,查看是否能读取到数据
4.修改url.py文件内容,如下所示
from django.conf.urls import url
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^admin/',admin.site.urls),
url(r'^list/',views.lists)
]
5.通过刘兰兰器访问’localhost:8000/list/’,在控制台可以看到以下结果,表示数据已经成功读取。
2.展示数据库中的内容
根据上面的步骤已经可以正确读取数据库中的数据,接下来要将数据展示到页面当中。
1.首先修改views.py的代码,如下所示
创建一个字典list_content用于存储读出来的数据,再使用render方法中的context将数据进行传输。
from django.db import connection
def lists(request):
mycursor = connection.cursor();
mycursor.execute('select * from student')
rows = mycursor.fetchall()
list_content = {
"students":rows
}
return render(request,'list.html',context=list_content)
2.修改’list.html’页面进行布局
css布局
<style type="text/css">
table
{
border-collapse: collapse;
margin: 0 auto;
text-align: center;
}
table td, table th
{
border: 1px solid #cad9ea;
color: #666;
height: 30px;
}
table thead th
{
background-color: #CCE8EB;
width: 100px;
}
table tr:nth-child(odd)
{
background: #fff;
}
table tr:nth-child(even)
{
background: #F5FAFA;
}
</style>
html页面布局
<body>
<h1>学生</h1>
<hr>
<br>
<table width="90%" class="table">
<tr>
<th>序号</th>
<th>Id</th>
<th>姓名</th>
<th>年龄</th>
</tr>
{% for student in students %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{student.0}}</td>
<td>{{student.1}}</td>
<td>{{student.2}}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
结果如下所示