ubuntu18.04 django 连接 mysql 数据库方法和常见错误总结

本人电脑系统 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 pymysql
pymysql.install_as_MySQLdb()

(4)在你新建的 app 下的 models.py 文件中添加新建的数据库字段信息,如下所示:

class User(models.Model):
    username = models.CharField(max_length=32)  # varchar(32)
    password = models.CharField(max_length=32)  # varchar(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 -p
use 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):
    # 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.decode(errors='replace')
    return query

根据错误信息提示,说明 if 语句执行时出错, query 是 str 类型,而 decode() 是用来将 bytes 转换成 string 类型用的,由于 query 不需要解码,所以直接将 if 语句注释掉就可以了

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.decode(errors='replace')
    return query

解决方法参考资料:https://www.cnblogs.com/dbf-/p/10838176.html

本人学习 django 看到的是B站上的视频,我看的这个视频老师讲的特别详细,推荐给大家。

学习 django 推荐视频教程:https://www.bilibili.com/video/BV1JE411V7xk?p=1

原文地址:https://www.cnblogs.com/ttweixiao-IT-program/p/14066347.html