MySqlDB官网只支持Python3.4,这里Python3.5使用第三方库PyMysql连接Mysql数据库。
PyMysql下载地址:
https://pypi.python.org/pypi/PyMySQL#downloads
indows下安装方法:
下载解压后,进入PyMySql-0.6.7目录,执行python setup.py install安装
测试连接
import pymysql
conn = pymysql.connect(host='localhost', port=3306,user='root',passwd='rusky',db='mysql',charset='UTF8')
cur = conn.cursor()
cur.execute("select version()")
for i in cur:
print(i)
cur.close()
conn.close()
>>> from django.db import connection
>>> cursor = connection.cursor()
假如出现报错,不能在命令行执行,要在django的浏览器进行,要view.py写
from django.db import connection
from django.shortcuts import render_to_response
def current_datetime(request):
cursor = connection.cursor()
cursor.execute("SELECT VERSION()")
now = [row[0] for row in cursor.fetchall()]
return render_to_response('current_datetime.html',{'current_date' : now})
settings.py 设置模板目录
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
#'DIRS': [os.path.join(os.path.dirname(__file__),'templates').replace('\\','/')],
'DIRS': [os.path.join(os.path.dirname(__file__),'../mysite/templates').replace('\\','/')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
在模板目录下增加,current_datetime.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
It is now {{ current_date }} in html
</body>
</html>
运行cmd,python manage.py runserver,如果报错运行 python manage.py migrate
http://127.0.0.1:8000/current_datetime/
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', #数据库引擎
'NAME': 'test', #数据库名
'USER': 'root', #用户名
'PASSWORD': 'root', #密码
'HOST': '', #数据库主机,默认为localhost
'PORT': '', #数据库端口,MySQL默认为3306
'OPTIONS': {
'autocommit': True,
},
}
}
o.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
打开__init__.py,添加如下:
import pymysql
pymysql.install_as_MySQLdb()
------------------------------
插入数据库出现乱码
# coding:utf-8
浙公网安备 33010602011771号