当前位置: 首页>编程语言>正文

django和mysql mysqlclient版本 mysql和django连接

1、创建一个示例数据库

#创建数据库
mysql> create DATABASE django;
Query OK, 1 row affected (0.11 sec)

#选择数据库
mysql> use django;
Database changed

#创建数据表
mysql> create TABLE django_tbl(
    -> age INT);
Query OK, 0 rows affected (0.21 sec)

#插入数据
mysql> insert into django_tbl (age) VALUES (12);
Query OK, 1 row affected (0.10 sec)

mysql> select* from django_tbl;
+------+
| age  |
+------+
|   12 |
+------+
1 row in set (0.00 sec)

2、安装pymysql

pip install pymysql

3、在工程下的__init__.py导入库 

import  pymysql

pymysql.install_as_MySQLdb()

django和mysql mysqlclient版本 mysql和django连接,django和mysql mysqlclient版本 mysql和django连接_mysql,第1张

4、在settings.py中设置mysql的链接信息

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django',
        'USER': 'root',
        'PASSWORD': 'lmx082902*',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}

 

django和mysql mysqlclient版本 mysql和django连接,django和mysql mysqlclient版本 mysql和django连接_mysql_02,第2张

5、连接mysql创建对应数据库

#管理员身份允许cmd

C:\Users\Administrator>mysql -u root -p
Enter password: **********
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 16
Server version: 8.0.12 MySQL Community Server - GPL

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> create database bbs;
Query OK, 1 row affected (0.07 sec)

 

6、修改应用下models.py

# Create your models here.
"""
创建学生信息表模型
"""
from django.db import models

"""
 该类是用来生成数据库的 必须要继承models.Model
"""
class Student(models.Model):
    """
    创建如下几个表的字段
    """
    # 学号 primary_key=True: 该字段为主键
    studentNum = models.CharField('学号', primary_key=True, max_length=15)
    # 姓名 字符串 最大长度20
    name = models.CharField('姓名', max_length=20)
    # 年龄 整数 null=False, 表示该字段不能为空
    age = models.IntegerField('年龄', null=False)
    # 性别 布尔类型 默认True: 男生 False:女生
    sex = models.BooleanField('性别', default=True)
    # 手机 unique=True 该字段唯一
    mobile = models.CharField('手机', unique=True, max_length=15)
    # 创建时间 auto_now_add:只有在新增的时候才会生效
    createTime = models.DateTimeField(auto_now_add=True)
    # 修改时间 auto_now: 添加和修改都会改变时间
    modifyTime = models.DateTimeField(auto_now=True)

    # 指定表名 不指定默认APP名字——类名(app_demo_Student)
    class Meta:
        db_table = 'student'


"""
学生社团信息表
"""
class studentUnion(models.Model):
    # 自增主键, 这里不能设置default属性,负责执行save的时候就不会新增而是修改元素
    id = models.IntegerField(primary_key=True)
    # 社团名称
    unionName = models.CharField('社团名称', max_length=20)
    # 社团人数
    unionNum = models.IntegerField('人数', default=0)
    # 社团负责人 关联Student的主键 即studentNum学号 一对一的关系,on__delete 属性在django2.0之后为必填属性后面会介绍
    unionRoot = models.OneToOneField(Student, on_delete=None)

    class Meta:
        db_table = 'student_union'


"""
OneToOneField: 一对一
ForeignKey: 一对多
ManyToManyField: 多对多(没有ondelete 属性)
"""

7、执行迁移

#在数据库中创建了admin、auth等应用所需要的数据表

python manage.py  migrate

 

django和mysql mysqlclient版本 mysql和django连接,django和mysql mysqlclient版本 mysql和django连接_django_03,第3张

mysql> show tables;
+----------------------------+
| Tables_in_bbs              |
+----------------------------+
| auth_group                 |
| auth_group_permissions     |
| auth_permission            |
| auth_user                  |
| auth_user_groups           |
| auth_user_user_permissions |
| django_admin_log           |
| django_content_type        |
| django_migrations          |
| django_session             |
+----------------------------+
10 rows in set (0.00 sec)

mysql>

迁移过程中出现以下错误说明没有该数据库,需要创建数据库

self.connect()
  File "D:\Program(X86_64)\Python\lib\site-packages\pymysql\connections.py", line 633, in connect
    self._request_authentication()
  File "D:\Program(X86_64)\Python\lib\site-packages\pymysql\connections.py", line 932, in _request_authentication
    auth_packet = _auth.caching_sha2_password_auth(self, auth_packet)
  File "D:\Program(X86_64)\Python\lib\site-packages\pymysql\_auth.py", line 239, in caching_sha2_password_auth
    pkt = conn._read_packet()
  File "D:\Program(X86_64)\Python\lib\site-packages\pymysql\connections.py", line 725, in _read_packet
    packet.raise_for_error()
  File "D:\Program(X86_64)\Python\lib\site-packages\pymysql\protocol.py", line 221, in raise_for_error
    err.raise_mysql_exception(self._data)
  File "D:\Program(X86_64)\Python\lib\site-packages\pymysql\err.py", line 143, in raise_mysql_exception
    raise errorclass(errno, errval)
django.db.utils.OperationalError: (1049, "Unknown database 'django'")
mysql> \d
ERROR:
DELIMITER must be followed by a 'delimiter' character or string
mysql> create database django;
Query OK, 1 row affected (0.10 sec)

mysql>

 

8、迁移文件

makemigrations会检测应用目录下是否存在migrations目录,如果没有则进行创建。会根据应用的结构定义生成一个0001_initial.py文件,执行migrate命令就可以创建数据表了。
   每一次表结构的定义修改,都需要再次执行makemigrations命令,会重新生成一个新的数据库迁移文件,记录表结构之间的差异,执行migrate命令时会让新的迁移文件生效。
   django会把每一次数据迁移记录到django_migrations表中,每一次 执行migrate前都会比较迁移文件是否已经记录在表中了,只有没出现过的才会执行。


 python manage.py makemigrations

django和mysql mysqlclient版本 mysql和django连接,django和mysql mysqlclient版本 mysql和django连接_django_04,第4张

mysql> select * from django_migrations;
+----+--------------+------------------------------------------+----------------------------+
| id | app          | name                                     | applied                    |
+----+--------------+------------------------------------------+----------------------------+
|  1 | contenttypes | 0001_initial                             | 2021-05-05 06:56:32.461434 |
|  2 | auth         | 0001_initial                             | 2021-05-05 06:56:35.427440 |
|  3 | admin        | 0001_initial                             | 2021-05-05 06:56:36.325694 |
|  4 | admin        | 0002_logentry_remove_auto_add            | 2021-05-05 06:56:36.347685 |
|  5 | admin        | 0003_logentry_add_action_flag_choices    | 2021-05-05 06:56:36.367672 |
|  6 | contenttypes | 0002_remove_content_type_name            | 2021-05-05 06:56:36.804290 |
|  7 | auth         | 0002_alter_permission_name_max_length    | 2021-05-05 06:56:37.115109 |
|  8 | auth         | 0003_alter_user_email_max_length         | 2021-05-05 06:56:37.175444 |
|  9 | auth         | 0004_alter_user_username_opts            | 2021-05-05 06:56:37.233449 |
| 10 | auth         | 0005_alter_user_last_login_null          | 2021-05-05 06:56:37.461381 |
| 11 | auth         | 0006_require_contenttypes_0002           | 2021-05-05 06:56:37.479370 |
| 12 | auth         | 0007_alter_validators_add_error_messages | 2021-05-05 06:56:37.498358 |
| 13 | auth         | 0008_alter_user_username_max_length      | 2021-05-05 06:56:37.740620 |
| 14 | auth         | 0009_alter_user_last_name_max_length     | 2021-05-05 06:56:38.276865 |
| 15 | auth         | 0010_alter_group_name_max_length         | 2021-05-05 06:56:38.333087 |
| 16 | auth         | 0011_update_proxy_permissions            | 2021-05-05 06:56:38.357071 |
| 17 | auth         | 0012_alter_user_first_name_max_length    | 2021-05-05 06:56:38.671544 |
| 18 | sessions     | 0001_initial                             | 2021-05-05 06:56:38.840235 |
+----+--------------+------------------------------------------+----------------------------+
18 rows in set (0.00 sec)

mysql>

 


https://www.xamrdz.com/lan/5y61962746.html

相关文章: