博客
关于我
python测试开发django-10.django连接mysql
阅读量:475 次
发布时间:2019-03-06

本文共 4461 字,大约阅读时间需要 14 分钟。

前言

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": 打开报错给的地址404

解决办法,指定1.3.10版本安装

pip install mysqlclient==1.3.10

C:\Users\dell>pip install mysqlclient==1.3.10Collecting 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/sInstalling collected packages: mysqlclientSuccessfully 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.pyfrom 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 migrateOperations to perform:  Apply all migrations: admin, auth, contenttypes, hello, sessionsRunning 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 helloNo changes detected in app 'hello'

再创建hello这个app应用的表结构

python manage.py migrate hello

D:\web_djo\helloworld>python manage.py migrate helloOperations to perform:  Apply all migrations: helloRunning migrations:  No migrations to apply.

操作数据库

在settings.py同一目录新建一个testdb.py文件

# -*- coding: utf-8 -*-from django.http import HttpResponsefrom 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 urlfrom django.urls import re_path, pathfrom . import view, testdburlpatterns = [    url(r'^testdb$', testdb.testdb),]

浏览器打开: 访问一次,数据库里面就会新增一条数据

查看数据库hello_test会新增数据

django交流QQ群:779429633

转载地址:http://cimbz.baihongyu.com/

你可能感兴趣的文章
MySQL 中锁的面试题总结
查看>>
MySQL 中随机抽样:order by rand limit 的替代方案
查看>>
MySQL 为什么需要两阶段提交?
查看>>
mysql 为某个字段的值加前缀、去掉前缀
查看>>
mysql 主从
查看>>
mysql 主从 lock_mysql 主从同步权限mysql 行锁的实现
查看>>
mysql 主从互备份_mysql互为主从实战设置详解及自动化备份(Centos7.2)
查看>>
mysql 主从关系切换
查看>>
MYSQL 主从同步文档的大坑
查看>>
mysql 主键重复则覆盖_数据库主键不能重复
查看>>
Mysql 事务知识点与优化建议
查看>>
Mysql 优化 or
查看>>
mysql 优化器 key_mysql – 选择*和查询优化器
查看>>
MySQL 优化:Explain 执行计划详解
查看>>
Mysql 会导致锁表的语法
查看>>
mysql 使用sql文件恢复数据库
查看>>
mysql 修改默认字符集为utf8
查看>>
Mysql 共享锁
查看>>
MySQL 内核深度优化
查看>>
mysql 内连接、自然连接、外连接的区别
查看>>