网上找了很多文档,关于django连接mysql,展示mysql数据库中例子比较少,下面是我自己写的例子
S1:创建项目
执行命令:django-admin.py startproject mysite
S2:创建app
执行命令:django-admin.py startapp polls
S3:设置数据库settings.py
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', #'NAME': os.path.join(BASE_DIR, 'test'),#database name 'NAME': 'test', 'USER':'root', 'PASSWORD':'123456', 'HOST': 'localhost', 'PORT': '3306', } }
S4:编写模型文件models.py
from django.db import models import MySQLdb import mysite.settings class student(models.Model): name = models.CharField(max_length = 20) age = models.CharField(max_length = 20) def __str__(self): return self.name
S5:编写views.py文件
# *-* coding: utf-8 *-* import sys reload(sys) sys.setdefaultencoding("utf-8") from django.shortcuts import render, render_to_response from polls.models import student from django.http import HttpResponse import MySQLdb import mysite.settings # Create your views here. def index(request): students = student.objects.all() name = "" for stud in students: name = stud.name break return render_to_response('index.html' , {'students':students , 'name':name})
S6:设置urls.py
from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', # Examples: # url(r'^$', 'mysite.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^blog/index/$' , 'polls.views.index'), )
S7:编写index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> </head> <body> <p>学生数据如下:</p> {{name}} <!-- <input type="submit" name="Button" value="展示数据" onclick="ajax_click()" /> --> <table border="10"> <tr> <th>姓名</th> <th>年龄</th> </tr> {% for student in students %} <tr > <td>{{student.name}}</td> <td>{{student.age}}</td> </tr> {% endfor %} </table> </body> </html>
一个简单的django连接mysql数据库,展示数据库中表的内容的例子就完成了