Quick answer: The public application import for the mysqlclient distribution is commonly MySQLdb; _mysql is a lower-level extension name and should not be guessed as the API. Check the active interpreter, installed distribution, import path, and driver documentation before changing code or installing a different connector.

NameError: name '_mysql' is not defined usually means code referenced the low-level _mysql extension without importing it, or the MySQL client package that provides it is not available in the active Python environment. In most application code, you should import the higher-level MySQLdb interface from mysqlclient instead of calling _mysql directly.
The fix depends on what the traceback shows. If your own code uses _mysql as a name, change the import. If a dependency expects it, confirm that mysqlclient is installed for the interpreter that runs the app. If your project intentionally uses a pure-Python driver, configure that driver explicitly.
Do not paste database passwords into debugging snippets. You can diagnose this error without connecting to a database by checking imports, package metadata, and local file names first.
Read the first project file in the traceback before changing packages. If the failing line is in your code, fix the import or driver setup there. If it is inside a third-party package, check that package’s documented database driver support before replacing it.
The mysqlclient documentation, mysqlclient PyPI page, importlib find_spec documentation, importlib.metadata documentation, and PyMySQL installation documentation are useful references.
Use MySQLdb For mysqlclient
The mysqlclient package is normally imported as MySQLdb. Start by checking that import instead of reaching for _mysql directly.
try:
import MySQLdb
except ImportError as error:
print("MySQLdb import failed")
print(error)
else:
print("MySQLdb import ok")
print(MySQLdb.__file__)
If this import fails, install or repair mysqlclient in the same Python environment that runs the application.
For most application code, MySQLdb is the interface you import. The _mysql extension is an implementation detail exposed by the driver package.
Check Whether _mysql Exists
Use importlib.util.find_spec() to check whether Python can locate the low-level extension.
import importlib.util
spec = importlib.util.find_spec("_mysql")
if spec is None:
print("_mysql extension not found")
else:
print("_mysql extension found")
print(spec.origin)
A missing spec points to a package or environment problem. A spec that points into your project directory may indicate local shadowing.
If the extension exists but the app still fails, look for code that references _mysql without importing it. That is a plain Python name lookup problem, not a database connection problem.
Check Installed Package Versions
Package metadata confirms what is installed in the active interpreter.
from importlib.metadata import PackageNotFoundError, version
for package in ["mysqlclient", "PyMySQL"]:
try:
print(package, version(package))
except PackageNotFoundError:
print(package, "not installed")
Run this check from the same virtual environment, server worker, notebook kernel, or command runner where the traceback appears.

Look For Local Shadowing
Local files can shadow packages and cause confusing import behavior. Check for names that collide with MySQL driver modules.
from pathlib import Path
project_root = Path.cwd()
for name in ["MySQLdb.py", "_mysql.py", "MySQLdb", "_mysql"]:
path = project_root / name
if path.exists():
print("possible shadow:", path)
If you find one, rename the local file or folder and remove stale __pycache__ files before restarting Python.
Target The Active Interpreter
When installing mysqlclient, target the interpreter that runs the app. Printing the command first avoids installing into a different Python environment.
import shlex
import sys
command = [sys.executable, "-m", "pip", "install", "mysqlclient"]
print(" ".join(shlex.quote(part) for part in command))
Some systems also need MySQL development headers before mysqlclient can build. Follow your operating system or hosting provider’s package instructions when the build step fails.
Build failures and import failures are different stages. A build failure happens while installing the package. An import failure happens after installation when Python tries to load the module.

Use PyMySQL Only By Choice
PyMySQL can emulate the MySQLdb import path for projects that intentionally use a pure-Python driver. Make this an explicit project decision, not a silent workaround.
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
print(MySQLdb.__name__)
This can help in environments where compiling mysqlclient is not practical, but it may have different performance and behavior characteristics. Test database code after changing drivers.
Do not mix drivers accidentally. Choose one driver path for the project, document it, and make sure the deployment environment installs the same package.
Fix Checklist
First, read the traceback and identify whether your code, a dependency, or a framework is referencing _mysql. Then check MySQLdb, find_spec("_mysql"), and package metadata in the active environment.
Next, fix local shadowing if the import path points into your project. If the package is missing, install mysqlclient for the interpreter that runs the app, then restart the process.
Finally, run a small import-only check before testing a real database connection. That separates driver installation problems from host, user, password, network, and permission issues.
Once imports pass, test the real connection with a limited account and a harmless query. Keep connection secrets outside the source code.
Separate Distribution And Import Names
A package installed with pip can expose a different Python import name. mysqlclient is a distribution, while application examples commonly import MySQLdb. Read the current package documentation and inspect installed metadata instead of assuming that a distribution name or private extension is importable directly.

Avoid Private Extension Assumptions
Names beginning with an underscore are often implementation details. Code that reaches directly into _mysql can break across versions or platforms even when the supported public driver works. Use the documented connection, cursor, and error APIs unless a low-level integration explicitly requires more.
Check The Interpreter That Runs Code
Run python -c with the exact executable used by the application, print sys.executable, and inspect the distribution through that interpreter. A successful pip command attached to another Python does not install the driver into the environment that imports it.

Check Native Dependencies Separately
mysqlclient may require system headers, a client library, compiler support, or platform-specific configuration. Distinguish an import NameError from an installation or dynamic-linker error, and record versions before changing the environment.
Choose An Alternate Driver Deliberately
PyMySQL and other connectors have different implementation, compatibility, and performance characteristics. Switching drivers means reviewing connection options, parameter styles, transaction behavior, escaping, and error handling; it is not a name-only replacement.
Test A Minimal Public Connection
Start with a public import and a configuration that does not print secrets. Test a local or controlled database, connection timeout, query parameters, transaction cleanup, and failure handling before integrating the driver into the full application.
The mysqlclient documentation describes its supported Python interface. Python’s importlib.metadata reference helps inspect installed distributions. Related guidance includes environment isolation and integration tests.
For related environment boundaries, compare package setup, safe diagnostics, and driver tests before changing a database connector.
Frequently Asked Questions
Why does name _mysql is not defined happen?
Code refers to the private _mysql extension name without importing or installing the package that provides it, or it is running in a different environment.
What should I import for mysqlclient?
Application code commonly imports MySQLdb, while the distribution installed with pip is named mysqlclient; follow the package’s public documentation rather than guessing a private module name.
How do I check the active MySQL Python environment?
Print sys.executable, inspect the installed distribution with the same interpreter, and run a minimal public import from that environment.
Can PyMySQL fix this error?
It is a different driver choice, not a drop-in repair for every mysqlclient or MySQLdb application; change the connection code deliberately and test compatibility.