本人電腦系統 ubuntu18.04 , django版本 2.2
在ubuntu電腦使用django連接mysql資料庫的時候遇到了一些問題,總結下來分享給大家。
django自帶的資料庫是 sqlite ,如果想要換成 Mysql 資料庫需要做的有以下幾個步驟:
(1)創建一個 myql 資料庫
(2)在 settings.py 中把
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }}改成
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'HelloWorld_django', 'HOST': 'localhost', 'PORT': '3306', 'USER': 'root', 'PASSWORD': '...', }}(3)在和你新建的django項目同名的文件夾下的 __init__.py 文件中添加如下語句,如我的 django 項目名稱叫 helloworld,那麼就在helloworld/helloworld文件夾下的 __init__.py 中添加如下語句:
import pymysqlpymysql.install_as_MySQLdb()(4)在你新建的 app 下的 models.py 文件中添加新建的資料庫欄位信息,如下所示:
class User(models.Model): username = models.CharField(max_length=32) password = models.CharField(max_length=32)(5)執行資料庫遷移的命令
python3 manage.py makemigrations
python3 manage.py migrate
以上步驟執行完了之後如果沒有錯誤提示說明 django 已經成功連接上了 mysql 資料庫。
我在運行過程中遇到了許多錯誤,並且找到了比較好的解決方法,分享給大家
錯誤1 :django.db.utils.OperationalError: (1698, "Access denied for user 'root'@'localhost'")
解決方法:
mysql> USE mysql;mysql> UPDATE user SET plugin='mysql_native_password' WHERE User='root';mysql> FLUSH PRIVILEGES;mysql> exit;解決方法參考資料:https://stackoverflow.com/questions/41542045/mysql-django-db-utils-operationalerror-1698-access-denied-for-user-root
錯誤2:django.db.utils.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)")
解決方法:
mysql -u root -puse mysql;ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'newpassword'; FLUSH PRIVILEGES;解決方法參考資料:https://stackoverflow.com/questions/50652587/django-db-utils-operationalerror-1045access-denied-for-user-rootlocalhost
錯誤3:django AttributeError: 'str' object has no attribute 'decode'
解決方法:
出現這個錯誤之後可以根據錯誤提示找到文件位置,打開 operations.py 文件,找到以下代碼:
def last_executed_query(self, cursor, sql, params): query = getattr(cursor, '_executed', None) if query is not None: query = query.decode(errors='replace') return query根據錯誤信息提示,說明 if 語句執行時出錯, query 是 str 類型,而 decode() 是用來將 bytes 轉換成 string 類型用的,由於 query 不需要解碼,所以直接將 if 語句注釋掉就可以了
def last_executed_query(self, cursor, sql, params): query = getattr(cursor, '_executed', None) return query解決方法參考資料:https://www.cnblogs.com/dbf-/p/10838176.html
本人學習 django 看到的是B站上的視頻,我看的這個視頻老師講的特別詳細,推薦給大家。
學習 django 推薦視頻教程:https://www.bilibili.com/video/BV1JE411V7xk?p=1