美文网首页
Django连接MySQL

Django连接MySQL

作者: fbckf | 来源:发表于2018-07-27 14:31 被阅读0次

    安装 MySQL

    # ubuntu 18.04 以下版本
    $ sudo apt install mysql-server
    

     ubuntu 18.04 只有 MySQL8.0 版本支持,而直接使用 apt install mysql-server 命令安装的是 5.7 版本, 正确的安装姿势是 这样的

    安装第三方库 pymysql

    $ pip install pymysql
    

    配置

    # settings.py
    ...
    import pymysql
    pymysql.install_as_MySQLdb()
    ...
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            # 数据库名称
            'NAME': 'fbckf',
            # 用户名称
            'USER': 'fbckf',
            #密码 填写登陆数据库的用户密码
            'PASSWORD': '******',
            # 主机名,空白表示但前主机
            'HOST': '',
            # 端口
            'PORT': '3306',
        }
    }
    ...
    

    数据库迁移之后会在指定数据库中生成表

    查看

    # 登陆 mysql 数据库
    $ mysql -u fbckf -p
    Enter password: 
    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 450
    Server version: 5.7.22-0ubuntu0.16.04.1 (Ubuntu)
    
    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> use fbckf;
    Reading table information for completion of table and column names
    You can turn off this feature to get a quicker startup with -A
    
    Database changed
    mysql> show tables;
    +-----------------------------+
    | Tables_in_fbckf             |
    +-----------------------------+
    | auth_group                  |
    | auth_group_permissions      |
    | auth_permission             |
    | django_admin_log            |
    | django_content_type         |
    | django_migrations           |
    | django_session              |
    | users_user_groups           |
    | users_user_user_permissions |
    +-----------------------------+
    11 rows in set (0.00 sec)
    
    mysql> 
    
    

    要注意一点,使用 django 连接 mysql 时,指定的数据库需要自己创建。连接 之后就可以直接在数据库中进行操作,修改数据

    相关文章

      网友评论

          本文标题:Django连接MySQL

          本文链接:https://www.haomeiwen.com/subject/yjxgmftx.html