FAQ > MySQL and Databases
How do I connect to MySQL with Python?
# ---------- Connect via network ----------
#!/usr/bin/env /Applications/MAMP/Library/bin/python
import mysql.connector
config = {
'user': 'root',
'password': 'root',
'host': '127.0.0.1',
'port': 3306,
'database': 'test',
'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 ----------
# ---------- Connect using an UNIX socket ----------
#!/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': 'test',
'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 using an UNIX socket ----------