使用MySQL数据库

阅读: 104923     评论:24

在实际生产环境,Django是不可能使用SQLite这种轻量级的基于文件的数据库作为生产数据库。一般较多的会选择MySQL。

下面介绍一下如何在Django中使用MySQL数据库。

一、安装MySQL

不建议在Windows中部署MySQL,建议迁移到Linux上来。

我这里使用的是ubuntu16.04。

安装命令:

sudo apt-get update
sudo apt-get install mysql-server mysql-client

中途,请设置root用户的密码。

安装完毕后,使用命令行工具,输入root的密码,进入mysql:

mysql -u root -p

提示如下:

[feixue@feixue-VirtualBox: ~]$ mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.20-0ubuntu0.16.04.1 (Ubuntu)

Copyright (c) 2000, 2017, 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> 

可以使用命令,先看看当前数据库系统内有哪些已经默认创建好了的数据库:

mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.04 sec)

假设我们的Django工程名字为'mysite',那么我们就创建一个mysite数据库,当然,名字其实随意,但是一样的更好记忆和区分,不是么?

CREATE DATABASE mysite CHARACTER SET utf8;

强调:一定要将字符编码设置为utf8,很多错误就是没正确设置编码导致的!

创建好mystie数据库后,可以用上面的命令,检查一下,没有问题,就退出mysql。

mysql> CREATE DATABASE mysite CHARACTER SET utf8;
Query OK, 1 row affected (0.00 sec)

mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysite             |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

mysql> exit;
Bye

二、配置MySQL服务

假设Django服务器所在主机的ip为192.168.1.100,而mysql服务所在机器的IP为192.168.1.121,为了能够从项目主机访问数据库主机,需要对MySQL服务进行配置。

打开配置文件:

sudo vim /etc/mysql/mysql.conf.d/mysqld.cnf

将下面一行注释掉:

# band-address = localhost
# .....

[mysqld]
#
# * Basic Settings
#
user            = mysql
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
port            = 3306
basedir         = /usr
datadir         = /var/lib/mysql
tmpdir          = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
#bind-address= localhost
skip-name-resolve
character-set-server=utf8

# .....

如果不这么做,将会出现error:1045 deny access,拒绝访问错误。

使用下面的命令,重新启动mysql服务:

sudo service mysql restart

三、安装Python访问MySQL的模块

Django官方已经不建议使用pymysql库了,而是改用mysqlclient,直接pip安装即可。

pip install mysqlclient

四、配置Django的settings.py

在Django的settings.py文件中设置如下:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',   # 数据库引擎
        'NAME': 'mysite',  # 数据库名,先前创建的
        'USER': 'root',     # 用户名,可以自己创建用户
        'PASSWORD': '****',  # 密码
        'HOST': '192.168.1.121',  # mysql服务所在的主机ip
        'PORT': '3306',         # mysql服务端口
    }
}

至此,就可以像使用SQLite一样使用MySQL了!

四、注意网络和权限问题

由于各种各样的原因,很多新手在第一次部署MySQL服务器的时候,总是会出现问题。下面将一些排查手段列出:

  • 确保你的Linux发行版没有给你挖坑,不要选小众版本
  • 确保MySQL的版本合格,越新越好
  • 确保Django服务器主机能访问MySQL主机
  • 查看防火墙、端口、用户权限、虚拟机桥接和NAT
  • 通过ssh、ping等一切手段验证网络是畅通的
  • 确保mysqlclient库是最新可用的
  • 确保mysqlclient被安装在了正确的虚拟环境中
  • 通过navicat确保Mysql服务启动并正常工作
  • 确保mysite数据库被正确安装了
  • 确保mysite数据库对当前Django服务器IP发出的,以数据库用户名登录的用户具有正确的权限
  • 确保数据库用户名和密码正确
  • 确保你使用的数据库用户对我们创建的mysqite数据库有读写权限
  • 确保数据库是utf-8模式

总之:

  • 服务可用
  • 网络可达
  • 权限满足
  • 模式正确

以上,都不是Django的锅,如果还是有问题,请提高自己的Linux管理技能和MySQL知识。


 核心配置项 django-admin和manage.py 

评论总数: 24


点击登录后方可评论

说说window中mysql的配置把 都是上班学习 没有LINUX的环境



NameError: name '_mysql' is not defined 报这个错,度娘了一下是因为Mysqldb 不兼容 python3.5 以后的版本 我使用的python3.10 说需要换成pymysql,有没有不换的方案?



报错信息: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? 解决方案: yum install -y python3-devel mysql-devel pip install mysqlclient 参考: https://cloud.tencent.com/developer/article/1755110



请问配置好数据库,你不用执行迁移操作吗



请问mysql中的某一个数据如何传递到html前端?例如只传递ID=1的数据该怎么操作?



打卡



你好,我想请问一下,如果我想把威胁你小程序前端的内容存到自己服务器,django setting中的host改怎么写?



你好,在ubantu操作系统下django使用mysql配置跟你上面的一样,但是执行python manage.py makemigrations 时会报错:段错误 (核心已转储) 请问这样该如何解决?



从未遇到过类似问题。网络搜索一下吧。



如果使用anaconda创建虚拟环境并安装django后,在虚拟环境中使用conda list命令,如果已经安装了mysqlclient的千万不要安装并引用pymysql这个包。不使用pymysql这个包的话django会默认使用更新一点的mysqlclient进行连接,如果写了 import pymsql 和pymysql.install_as_MySQLdb()这两句后,django会使用pymysql进行连接数据库,而pymysql的mysqlclient版本就是0.9.3。也就是各位报错的,“django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.”这句话的来源。希望博主可以稍微修改一下。 今天我也在部署django到lnmp环境中,提几个容易踩的坑,警示自己,也为后来人铺一下道路: 1.使用远程数据库提示Internet error,查看远程数据库的对应端口是否开放(比如MySQL就是3306,需要看一下防火墙有没有放行3306) 2.能访问3306端口但远程无法使用数据库,查看用户是否具有任意主机访问数据库的权限 3.提示django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3. 在没有其他使用的情况下将代码中的pymysql全部删掉。不需要安装pymysql。如果不是像我使用conda创建的虚拟环境的,可以使用pip安装最新mysqlclient即可解决。



很好的建议和经验,已经修改,谢谢。



我也踩过坑 点个赞



这个坑我也刚踩完,挣扎了好几个小时。“django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.” 这句话在都不想看。



你好,运行后显示'DatabaseWrapper' object has no attribute 'corsor' 是什么原因啊



你好,前两个问题已经按照注释和修改encode解决了,但只要makemigrations就会报错ValueError: source code string cannot contain null bytes,文件放到word里也没发现有多的字符,而只要在settings里改成用sqlite就不会报这个错,请问这个要怎么解决啊,网上搜了一天也没发现该怎么解决,求帮助,谢谢!



您好!我也遇到了这个问题,不知道您当时是怎样解决的?谢谢



按照文中配置,报错django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3. 有木有爬过这个坑的



已解决: 1、raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__)    django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.   解决办法:C:\Python37\Lib\site-packages\django\db\backends\mysql(python安装目录)打开base.py,注释掉以下内容:        if version < (1, 3, 13):           raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__)    2、File "C:\Python37\lib\site-packages\django\db\backends\mysql\operations.py", line 146, in last_executed_query    query = query.decode(errors='replace')   AttributeError: 'str' object has no attribute 'decode'   解决办法:打开此文件把146行的decode修改为encode



只有这一种解决办法吗?



应该不是。不需要引入pymysql这个包,这个包默认是0.9.3(眼熟不)。其实只要装了mysqlclient之后,默认版本是1.4以上的。(博主强调不能省略的两句话全去掉就好了)



https://blog.csdn.net/zztingfeng/article/details/80155624 把相关检查代码注释就OK了



出现出现 2003-Can’t connect to MySQL on ’192.168.1.2’(10061); 我是使用了虚拟环境,现在虚拟内存对应的python下载了pymysql库,但是却显示不行



/usr/bin/python3.5 /home/qly/PycharmProjects/remb/manage.py runserver 127.0.0.1:8000 Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f188468ad90> Traceback (most recent call last): File "/home/qly/.local/lib/python3.5/site-packages/django/db/utils.py", line 110, in load_backend return import_module('%s.base' % backend_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 944, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked ImportError: No module named 'django.db.backends.mysql' The above exception was the direct cause of the following exception:



踩过坑的,点个赞~!