Python and MySQL with MySQLdb

Last week I was looking for a Python module that I could use to interact with a MySQL database server. MySQLdb is doing just that.

“MySQLdb is a thin Python wrapper around _mysql which makes it compatible with the Python DB API interface (version 2). In reality, a fair amount of the code which implements the API is in _mysql for the sake of efficiency.”

To install and use it, simply run: sudo apt-get install python-mysqldb

When that is done, you can start importing the MySQLdb module in your scripts.

I found this code snippet on Alex Harvey website

# Make the connection
connection = MySQLdb.connect(host='localhost',user='alex',passwd='secret',db='myDB')
cursor = connection.cursor()

# Lists the tables in demo
sql = "SHOW TABLES;"

# Execute the SQL query and get the response
response = cursor.fetchall()

# Loop through the response and print table names
for row in response:
    print row[0]

For more examples on how to use MySQLdb in Python, please take a look on

Leave a Reply

Your email address will not be published.