前言
Django 對各種數據庫提供了很好的支持,包括:PostgreSQL、MySQL、SQLite、Oracle。本篇以mysql為例簡單介紹django連接mysql進行數據操作
Django連mysql需要安裝驅動mysqlclient
mysqlclient安裝
先要安裝數據庫驅動mysqlclient,使用pip安裝就行
pip install mysqlclient
copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.6\MySQLdb\constants
copying MySQLdb\constants\REFRESH.py -> build\lib.win-amd64-3.6\MySQLdb\constants
running build_ext
building '_mysql' extension
error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools
----------------------------------------
Command "e:\python36\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\dell\\AppData\\Local\\Temp\\pip-install-trc0p4gc\\mysqlclient\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\dell\AppData\Local\Temp\pip-record-ulwogpct\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\dell\AppData\Local\Temp\pip-install-trc0p4gc\mysqlclient\
這里我安裝的時候出現了報錯:“Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools” 打開報錯給的地址404
解決辦法,指定1.3.10版本安裝
pip install mysqlclient==1.3.10
C:\Users\dell>pip install mysqlclient==1.3.10
Collecting mysqlclient==1.3.10
Downloading https://files.pythonhosted.org/packages/c8/e0/e38c1fc71355bbc60e89401674bc0190f39a207f0235bb92b7e7b09948d0/mysqlclient-1.3.10-cp36-cp36m-win_amd64.whl (1.4MB)
100% |████████████████████████████████| 1.4MB 466kB/s
Installing collected packages: mysqlclient
Successfully installed mysqlclient-1.3.10
django配置數據庫
settings.py 文件中找到 DATABASES 配置項, django默認連接sqllite。ENGINE:是指連接數據庫驅動的名稱,有以下幾種情況:
- django.db.backends.postgresql 連接 PostgreSQL
- django.db.backends.mysql 連接 mysql
- django.db.backends.sqlite3 連接 sqlite
- django.db.backends.oracle 連接 oracle
這里我們連接mysql需要賬戶密碼,也就是之前安裝mysql的root用戶名,和自己設置的密碼,NAME是數據庫的名稱,連接配置如下:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # 或者使用 mysql.connector.django
'NAME': 'test',
'USER': 'root',
'PASSWORD': 'yoyo',
'HOST':'localhost',
'PORT':'3306',
}
}
創建表,同步到mysql
類名代表了數據庫表名,且繼承了models.Model,類里面的字段代表數據表中的字段(name),數據類型則由CharField(相當於varchar)、DateField(相當於datetime), max_length 參數限定長度。
# models.py
from django.db import models
# Create your models here.
class Test(models.Model):
name = models.CharField(max_length=20)
先創建表結構,在數據庫里面新增一些表
python manage.py migrate
D:\web_djo\helloworld>python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, hello, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying hello.0001_initial... OK
Applying hello.0002_auto_20181122_1025... OK
Applying hello.0003_auto_20181122_1033... OK
Applying sessions.0001_initial... OK
打開數據庫,會發現多了一些表名稱,hello_test就是上一步新建的表
接着讓 Django 知道我們在我們的模型有一些變更
python manage.py makemigrations hello
D:\web_djo\helloworld>python manage.py makemigrations hello
No changes detected in app 'hello'
再創建hello這個app應用的表結構
python manage.py migrate hello
D:\web_djo\helloworld>python manage.py migrate hello
Operations to perform:
Apply all migrations: hello
Running migrations:
No migrations to apply.
操作數據庫
在settings.py同一目錄新建一個testdb.py文件
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from hello.models import Test
# 數據庫操作
def testdb(request):
test1 = Test(name='yoyo1')
test1.save()
return HttpResponse("數據庫hello_test添加name成功!看去看看吧")
urls.py配置訪問地址
from django.conf.urls import url
from django.urls import re_path, path
from . import view, testdb
urlpatterns = [
url(r'^testdb$', testdb.testdb),
]
瀏覽器打開:http://127.0.0.1:8000/testdb 訪問一次,數據庫里面就會新增一條數據
查看數據庫hello_test會新增數據
django交流QQ群:779429633