如何解决Python中oracledb库的DPY-4001: no password specified错误
That error DPY-4001: no password specified boils down to one simple issue: your pw variable is coming up as None—meaning the PYTHON_PASSWORD environment variable you're trying to read either doesn't exist, is empty, or isn't being picked up by your Jupyter session. Let's walk through the fixes step by step:
1. Verify your environment variables are actually set
First, check what your code is actually getting by running this quick test in Jupyter:
import os print("Username:", os.environ.get('PYTHON_USERNAME')) print("Password:", os.environ.get('PYTHON_PASSWORD')) print("Connect String:", os.environ.get('PYTHON_CONNECTSTRING'))
If any of these print None, that's your problem.
On Windows, environment variables set after launching Jupyter won't be picked up. You need to:
- Open an Anaconda Prompt first
- Set the variables there with commands like:
set PYTHON_USERNAME=your_real_username set PYTHON_PASSWORD=your_real_password set PYTHON_CONNECTSTRING=your_db_host:port/service_name - Then launch Jupyter Notebook from that same prompt.
2. Quick test: Hardcode credentials (for testing only!)
To rule out environment variable issues entirely, temporarily replace the environment variable calls with your actual credentials (never do this in production code):
import oracledb un = "your_real_username" pw = "your_real_password" cs = "your_db_host:port/service_name" # e.g., "localhost:1521/orclpdb" with oracledb.connect(user=un, password=pw, dsn=cs) as connection: with connection.cursor() as cursor: sql = """select sysdate from dual""" for r in cursor.execute(sql): print(r)
If this works, you know the original issue was definitely with environment variable loading.
3. Better long-term solution: Use a .env file
For a secure, flexible way to manage credentials without cluttering system environment variables, use python-dotenv:
- Install the package in your Anaconda environment:
pip install python-dotenv - Create a
.envfile in your project folder with these lines:PYTHON_USERNAME=your_real_username PYTHON_PASSWORD=your_real_password PYTHON_CONNECTSTRING=your_db_host:port/service_name - Update your code to load the
.envfile:import oracledb from dotenv import load_dotenv import os load_dotenv() # Loads variables from .env into the environment un = os.environ.get('PYTHON_USERNAME') pw = os.environ.get('PYTHON_PASSWORD') cs = os.environ.get('PYTHON_CONNECTSTRING') with oracledb.connect(user=un, password=pw, dsn=cs) as connection: with connection.cursor() as cursor: sql = """select sysdate from dual""" for r in cursor.execute(sql): print(r)
Also double-check that your connection string cs is formatted correctly—common formats are hostname:port/service_name or a full TNS entry. If that's incorrect, you'll hit a different error, but it's worth confirming while you're troubleshooting.
内容的提问来源于stack exchange,提问作者Kevin Tracey

