Django配置MySQL数据库后无法连接,执行django-admin dbshell报错
dbshell Hey there, let's break down why you're hitting this error when running django-admin dbshell. First, let's confirm your database config from settings.py:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'investors_data', 'USER': 'root', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '3306', } }
Since your traceback got cut off, I'll walk through the most common fixes for this exact scenario:
Install the required MySQL database driver
Django's MySQL backend doesn't come with a driver out of the box. You'll need eithermysqlclient(the official, recommended option) orpymysqlinstalled. Run one of these commands based on your package manager:- For pip:
pip install mysqlclient - If you hit issues with mysqlclient (common on Windows), try
pip install pymysqland add this code at the very top of yoursettings.pyto patch it for Django:import pymysql pymysql.install_as_MySQLdb()
- For pip:
Verify the
investors_datadatabase exists
Django won't create your database automatically—you need to make it yourself first. Open a manual MySQL shell (runmysql -u root -pin your terminal) and run:CREATE DATABASE investors_data;Make sure the name matches exactly what's in your
NAMEconfig (case-sensitive on some systems!).Double-check your MySQL credentials
- Is your root user really using an empty password? Most MySQL setups require a password for root—try entering your actual root password in the
PASSWORDfield (wrap it in quotes if it has special characters). - Confirm MySQL is running on
127.0.0.1:3306—if you're using a local MySQL server, this is usually correct, but if you're running it in a container or remote server, you'll need to update these values.
- Is your root user really using an empty password? Most MySQL setups require a password for root—try entering your actual root password in the
Check root user permissions
Sometimes the root user isn't allowed to connect from127.0.0.1(unlikely, but possible). To fix this, run these commands in your MySQL shell:GRANT ALL PRIVILEGES ON investors_data.* TO 'root'@'127.0.0.1'; FLUSH PRIVILEGES;
Once you've tried these steps, run django-admin dbshell again—this should get you connected. If you still get an error, share the full traceback and we can dig deeper!
内容的提问来源于stack exchange,提问作者nishant singh

