環境:python三、Django2html
一、安裝驅動mysqlclientpython
pip3 install mysqlclient
二、建立一個數據庫mysql
CREATE DATABASE database_name CHARACTER SET UTF8; 指定數據庫的編碼utf8
三、建立項目linux
django-admin startproject myweb #創建項目 cd myweb django-admin startapp myapp #創建項目下屬APP
四、APP下的models.py文件中加入表結構(django中之因此把表結構在自身文件中定義,是爲了在其餘文件中可直接引用表結構進行數據庫操做,不用頻繁刷新數據表獲取表結構)web
from django.db import models # Create your models here. class book_info(models.Model): fromuser = models.CharField(max_length=30, default='WYS') fromsite = models.CharField(max_length=50) bookname = models.CharField(max_length=50) #updatetime = models.DateTimeField() #lastchapter = models.CharField(max_length=100) class site_info(models.Model): sitename = models.CharField(max_length=50) bookname = models.CharField(max_length=50) url = models.CharField(max_length=200) updatetime = models.DateTimeField() lastchapter = models.CharField(max_length=100)
5.在myweb/myweb/settings.py中加入建立的APP和MYSQL鏈接信息sql
INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', )
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'test', 'USER': 'test', 'PASSWORD': 'test', 'HOST': 'localhost', 'PORT': '3306', } }
6.將models.py中的數據庫表結構同步到MYSQL中shell
python manage.py migrate #建立表結構 python manage.py makemigrations myapp #告訴django,myapp中的表結構有更新 python manage.py migrate myapp #執行myapp中的表結構到mysql中
數據庫中的表名爲myapp_book_info,myapp_site_info,但django代碼中調用時的表名爲models.py中定義的表名book_info,site_info數據庫
七、數據表操做-增刪改查,請參考mysql 鏈接 djangodjango
八、Django鏈接mysql出錯vim
錯誤一:No module named 'MySQLdb'
緣由:python3鏈接MySQL不能再使用mysqldb,取而代之的是pymysql。
解決方法:在python的MySQL包中,即路徑:C:\Users\adong\AppData\Local\Programs\Python\Python36\Lib\site-packages\Django-2.0.3-py3.6.egg\django\db\backends\mysql
下的__init__.py文件中加入:
import pymysql
pymysql.install_as_MySQLdb()
錯誤二:django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.3 or newer is required; you have 0.7.11.None
緣由:在解決了錯誤一之後出現了此錯誤。
解決方法:在python的MySQL包中,即路徑:C:\Users\adong\AppData\Local\Programs\Python\Python36\Lib\site-packages\Django-2.0.3-py3.6.egg\django\db\backends\mysql
# 找到base.py文件,註釋掉 base.py 中以下部分(35/36行) if version < (1, 3, 3): raise ImproperlyConfigured("mysqlclient 1.3.3 or newer is required; you have %s" % Database.__version__)
此時仍會會報錯,報錯信息以下:
AttributeError: ‘str’ object has no attribute ‘decode’
#找到operations.py文件(146行),將decode改成encode #linux vim 查找快捷鍵:?decode if query is not None: query = query.decode(errors='replace') return query #改成 if query is not None: query = query.encode(errors='replace') return query
OK~ 再也不報錯
參考: