How do I connect to MySQL with Python?
UNIX Socket (Recommended)
Section titled “UNIX Socket (Recommended)”#!/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 = Nonetry: 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()TCP/IP
Section titled “TCP/IP”#!/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 = Nonetry: 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()