Connect to MySQL from Python
Connection Parameters
Section titled “Connection Parameters”| Parameter | Value |
|---|---|
| Host (socket) | localhost |
| Host (TCP/IP) | 127.0.0.1 |
| Port | 8889 |
| Username | root |
| Password | root (unless changed in MAMP PRO) |
| Socket | /Applications/MAMP/tmp/mysql/mysql.sock |
Examples
Section titled “Examples”Use localhost as the host and provide the socket path explicitly. Faster than TCP/IP when script and database run on the same machine.
#!/usr/bin/env /Applications/MAMP/Library/bin/python
import mysql.connector
config = { 'user': 'root', 'password': 'root', 'host': 'localhost', 'unix_socket': '/Applications/MAMP/tmp/mysql/mysql.sock', 'database': 'mydatabase', 'raise_on_warnings': True}
cnx = mysql.connector.connect(**config)cursor = cnx.cursor(dictionary=True)cursor.execute('SELECT `id`, `name` FROM `test`')
for row in cursor.fetchall(): print('%s | %s' % (row['id'], row['name']))
cnx.close()Use 127.0.0.1 as the host and specify port 8889 explicitly. Required when a port must be provided or the connection is made over a network.
#!/usr/bin/env /Applications/MAMP/Library/bin/python
import mysql.connector
config = { 'user': 'root', 'password': 'root', 'host': '127.0.0.1', 'port': 8889, 'database': 'mydatabase', 'raise_on_warnings': True}
cnx = mysql.connector.connect(**config)cursor = cnx.cursor(dictionary=True)cursor.execute('SELECT `id`, `name` FROM `test`')
for row in cursor.fetchall(): print('%s | %s' % (row['id'], row['name']))
cnx.close()Troubleshooting
Section titled “Troubleshooting”Connection refused
Open MAMP PRO and verify that the MySQL server is active.
Access denied for user ‘root’
The username or password is incorrect. The default password is root, but if you changed it in MAMP PRO, use that password instead. See How to change the MySQL password.
Unknown database
The specified database does not exist. Create it first in phpMyAdmin or in MAMP PRO via the Databases tab.
Can’t connect to MySQL server on ‘127.0.0.1:3306’
MAMP PRO may not use port 3306. Check the configured port under Settings › Server › Ports and update your script accordingly (e.g. 'port': 8889).