小编典典

将MySQL与Django结合使用-用户'@'localhost的访问被拒绝

mysql

因此,我通过以下资源学习Django(1、3、1,“最终”,0):http
:
//www.djangobook.com/en/2.0/chapter05/

我通过Synaptic安装了“ mysql-server”和“ python-mysqldb”。我在settings.py中更改了相关设置。

上面提到的书告诉我们从manage.py shell运行:

>>> from django.db import connection
>>> cursor = connection.cursor()

运行以下命令后出现此错误:

OperationalError: (1044, "Access denied for user ''@'localhost' to database 'mydb'")

  Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/django/db/backends/__init__.py", line 250, in cursor
    cursor = self.make_debug_cursor(self._cursor())
  File "/usr/lib/python2.7/dist-packages/django/db/backends/mysql/base.py", line 322, in _cursor
    self.connection = Database.connect(**kwargs)
  File "/usr/lib/python2.7/dist-packages/MySQLdb/__init__.py", line 81, in Connect
    return Connection(*args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 187, in __init__
    super(Connection, self).__init__(*args, **kwargs2)
OperationalError: (1044, "Access denied for user ''@'localhost' to database 'mydb'")

MySQL确实要求我在首次安装时设置root密码,在这里可以使用吗?或者是别的什么?


阅读 295

收藏
2020-05-17

共1个答案

小编典典

您的用户无权访问数据库。使用以下命令来设置数据库。

DROP DATABASE IF EXISTS `mydb`;
CREATE DATABASE `mydb`
    DEFAULT CHARACTER SET utf8
    DEFAULT COLLATE utf8_general_ci;

USE 'mysql';
GRANT ALL PRIVILEGES ON mydb.* TO 'mydb_user'@'localhost' IDENTIFIED BY 'your_password'

WITH GRANT OPTION;
FLUSH PRIVILEGES;

另外,您需要具有足够的特权才能运行它。然后将其另存为script.sql,

$mysql -u root -p < script.sql

除了需要确保正确设置数据库设置的settings.py之外

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mydb',                  
        'USER': 'mydb_user',             
        'PASSWORD': 'your_password',                  
        'HOST': '',                     
        'PORT': '',                      
    }
}

python manage.py syncdb

到此为止。

2020-05-17