Search

FAQ > Python

Connecting to MySQL from your own scripts

How to connect to the MAMP PRO MySQL server from Python scripts using the correct host, port, and credentials.

Connection Parameters

Parameter Value
Host localhost / 127.0.0.1 (depending on language and/or connection method used)
Port 8889
Username root
Password root
Socket /Applications/MAMP/tmp/mysql/mysql.sock

Examples

Use localhost as the host and provide the socket path explicitly. This is faster than a TCP/IP connection and is recommended when your script and the database server 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`')
 
results = cursor.fetchall()
 
for row in results:
  id = row['id']
  title = row['name']
  print '%s | %s' % (id, title)
 
cnx.close()
Connect via Network (TCP/IP)

Use 127.0.0.1 as the host and specify port 8889 explicitly. This method is required when the connection is made over the network or when a port must be provided.

#!/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`')
 
results = cursor.fetchall()
 
for row in results:
  id = row['id']
  title = row['name']
  print '%s | %s' % (id, title)
 
cnx.close()

Which method should I use? The UNIX socket connection (localhost) is faster and recommended when your script and the database server run on the same machine. Use the TCP/IP connection (127.0.0.1 with port 8889) when a port must be specified explicitly or the connection is made over a network.

Troubleshooting

Connection refused
Open MAMP PRO and verify that the MySQL server status is shown as active.

Access denied for user ‘root’
The username or password is incorrect. The default credentials are root / root.

Unknown database
The specified database does not exist. Create it first in phpMyAdmin, or directly in MAMP PRO by selecting your site and opening the Databases tab.

Can’t connect to MySQL server on ‘127.0.0.1:3306’
MAMP PRO does not necessarily use the default MySQL port 3306. To verify which port is configured, open MAMP PRO and go to Settings → Server → Ports. Use that port number in your script (e.g. 'port': 8889).