Skip to content
MAMP PRO Documentation

How do I connect to MySQL with Python?

#!/usr/bin/env /Applications/MAMP/Library/bin/python
import mysql.connector
config = {
'user': 'root',
'password': 'root',
'unix_socket': '/Applications/MAMP/tmp/mysql/mysql.sock',
'database': 'test', # replace with your database name
'raise_on_warnings': True
}
cnx = None
try:
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']))
finally:
if cnx:
cnx.close()
#!/usr/bin/env /Applications/MAMP/Library/bin/python
import mysql.connector
config = {
'user': 'root',
'password': 'root',
'host': '127.0.0.1',
'port': 3306, # default MAMP PRO MySQL port
'database': 'test', # replace with your database name
'raise_on_warnings': True
}
cnx = None
try:
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']))
finally:
if cnx:
cnx.close()

MySQL how-to guides