PyMySQL无法连接本地数据库,PHP可正常连接本地phpMyAdmin求助
Hey there! Let's break down why your PyMySQL script can't connect to your local XAMPP MySQL database, even though your PHP script works perfectly. Based on your PHP code, here are the most likely fixes to try:
1. Fix the Host Address
Your PHP script uses localhost, but in Python/PyMySQL, localhost often tries to use a Unix socket instead of TCP/IP—and XAMPP's MySQL socket path rarely matches PyMySQL's default.
Quick fix: Replace localhost with 127.0.0.1 in your PyMySQL connection string. This forces a TCP/IP connection, which aligns with how PHP connects to XAMPP's MySQL in most setups.
2. Explicitly Specify the Port
XAMPP's MySQL defaults to port 3306, but if you've ever modified this port, you'll need to explicitly declare it in PyMySQL. PHP usually picks up the system default port automatically, but PyMySQL requires it if it's non-standard.
Fix: Add the port=3306 parameter (or your custom port number) to your PyMySQL connection.
3. Check User Permissions
Your root user might be configured to only allow connections via the local socket (which PHP uses) and not via TCP/IP. You'll need to grant explicit permissions for root@127.0.0.1 to access your Work database.
How to do this:
- Open phpMyAdmin through your XAMPP dashboard
- Navigate to the User accounts tab
- Look for the
rootuser entry linked to127.0.0.1(create it if it doesn't exist) - Grant all privileges on the
Workdatabase to this user - Save your changes
4. Working PyMySQL Connection Script
Here's a script that mirrors your PHP connection settings, with the fixes above included:
import pymysql try: conn = pymysql.connect( host='127.0.0.1', # Force TCP/IP connection user='root', password='', # Match your empty PHP password database='Work', port=3306 # Default XAMPP MySQL port ) print("Connection successful!") conn.close() except pymysql.MySQLError as e: print(f"Connection failed: {e}")
5. Final Checks
- Double-check that XAMPP's MySQL service is running (you mentioned starting XAMPP, but a quick dashboard verification never hurts)
- Ensure no local firewall is blocking port 3306
- Confirm PyMySQL is installed correctly (run
pip install pymysqlif you haven't already)
If you still hit an error, share the exact error message from PyMySQL—it'll help narrow down the issue even further!
内容的提问来源于stack exchange,提问作者Outcast

