安裝好MySQL之后,直接用Python進行操作是可以的,假設要在django中使用mysql,還需要安裝pymysql,話不多說,直接安裝:
pip3 install pymysql --user
安裝完之后,在setting進行如下配置:
1、首先在django工程的setting.py里,引入pymysql:
import os import pymysql pymysql.install_as_MySQLdb()
2、接着,在mysql里創建一個數據庫,用來存儲django里要存取的表格:
lzh@lzh-pc:~$ mysql -u root -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 9 Server version: 8.0.17 MySQL Community Server - GPL Copyright (c) 2000, 2019, 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 test_app CHARACTER SET utf8; Query OK, 1 row affected, 1 warning (0.01 sec) mysql> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | sys | | test_app | +--------------------+ 5 rows in set (0.00 sec)
3、最后,配置django工程里的setting.py的database部分。其中name是在mysql里定義的某個數據庫名:
# Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'test_app', 'USER': 'root', 'PASSWORD': '19830427', 'HOST': 'localhost', 'PORT': '3306', } }
4、高能預警!
此時無論是直接runserver,還是makemigrations,都會報錯,大致是:
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.
但是請注意,如果用pip3 list查看,是根本沒有mysqlclient這個包的,一定會有人想,如果沒有這個包(或者版本太低),裝一下不就行了。
5、安裝mysqlclient,官網上列舉了這些前置需求:
sudo apt-get install python3-dev
sudo apt-get install
default-libmysqlclient-dev
如果把這兩個安裝完成后,再安裝mysqlclient,仍然會報錯,而且會報錯一整屏幕紅字,非常驚悚,仔細一看,主要是這里的問題:
/usr/bin/ld: 找不到 -lssl /usr/bin/ld: 找不到 -lcrypto
安裝其中一個即可:sudo apt-get install libssl-dev
【注意是libssl,少一個l】
到這里,就能正常安裝mysqlclient了,使用命令:pip3 install mysqlclient --user
然后再用pip3 list就能查看到:
mysqlclient 1.4.4
到了這里,你以為問題解決了,然后能愉快地運行runserver或makemigrations?非常遺憾!
仍然會報錯:django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.
這就不是版本的問題了,而是它永遠都會出錯!!!
File "/home/lzh/.local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 36, in <module> 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.
6、大部分的人(網上看到的各種筆記,blog,經驗分享)都是選擇直接跳過這個錯誤,方法是編輯報錯文件:gedit /home/yourusername/.local/lib/python3.6/site-packages/django/db/backends/mysql/base.py
將以下兩行注釋掉:
# if version < (1, 3, 13): # raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__)
嘗試運行runserver或makemigrations,仍然出錯:
File "/home/lzh/.local/lib/python3.6/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'
解決這個報錯的方法是:gedit /home/lzh/.local/lib/python3.6/site-packages/django/db/backends/mysql/opetions.py
將decode改為encode,代碼為:
def last_executed_query(self, cursor, sql, params): # With MySQLdb, cursor objects have an (undocumented) "_executed" # attribute where the exact query sent to the database is saved. # See MySQLdb/cursors.py in the source distribution. query = getattr(cursor, '_executed', None) if query is not None: query = query.encode(errors='replace') return query
7、后記
安裝了MySQL,然后安裝了pymysql,就直接開始使用的,當報錯時直接使用《6》的方法解決即可,個人懷疑是檢查兼容性的代碼有bug;
實際上,在bug沒有解決前,費勁心思安裝mysqlclient一點用處沒有!
8、驗證django使用mysql
(1)使用python3 manage.py createsuperuser創建超級管理員
(2)進入admin后台,添加一個guest:guest_name=劉振華,guest_title=先生
(3)查看mysql是否有對應內容
lzh@lzh-pc:~$ mysql -u root -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 30 Server version: 8.0.17 MySQL Community Server - GPL Copyright (c) 2000, 2019, 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 test_app; 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_test_app | +----------------------------+ | 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 | | test_app_cnbcontent | | test_app_cnbtitle | | test_app_guestmodel | +----------------------------+ 13 rows in set (0.00 sec) mysql> select * from test_app_guestmodel; +----+------------+-------------+ | id | guest_name | guest_title | +----+------------+-------------+ | 1 | 劉振華 | 先生 | +----+------------+-------------+ 1 row in set (0.00 sec)