美文网首页我爱编程
django 连接数据库

django 连接数据库

作者: 鸟它鸟 | 来源:发表于2018-05-26 19:20 被阅读0次

django要连接数据库,额,不咋需要配置,看下吧

自行切换到虚拟环境中去
(python36env) [root@xxx01 data]# pip install mysqlclient  #装数据连接的模块
(python36env) [root@xxx01 ops]# vim ops/settings.py
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.sqlite3',
#         'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
#     }
# }


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django',   #数据库名称
        'USER': 'root',        #连接数据库的用户
        'PASSWORD': '123456',   #连接数据库的密码
        'HOST': '127.0.0.1',  #数据库IP地址
        'PORT': 3306,  #数据库服务端口
        'OPTIONS':{
            'init_command': 'SET default_storage_engine=INNODB;',
        },
    }
}

打开settings.py配置文件,然后替换原本使用的sqlite数据库,用mysql的字段替换,直接复制就成,注意修改连接信息

接下来,我们需要简单的操作下数据库,在我们要连接的数据库中将数据库建立出来

MariaDB [(none)]> create database django;
Query OK, 1 row affected (0.00 sec)

然后可以启动服务喽

(python36env) [root@xxx01 ops]# python manage.py  runserver 0.0.0.0:8000
Performing system checks...

System check identified no issues (0 silenced).

You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

May 26, 2018 - 11:17:03
Django version 1.11.13, using settings 'ops.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.

关于数据库的映射关系更新到数据库,见上一篇文章https://www.jianshu.com/p/8aaa38c1619a,其实orm操作数据的方式都一样,只是配置连接器的方式不太一样。

相关文章

网友评论

    本文标题:django 连接数据库

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