Dec. 03, 2012

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

Share this article

Recommended Python Training – DataCamp

For Python training, our top recommendation is DataCamp.

Datacamp provides online interactive courses that combine interactive coding challenges with videos from top instructors in the field.

Datacamp has beginner to advanced Python training that programmers of all levels benefit from.


Download Our Free Guide To Learning Python

* indicates required

Read more about:
Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission. Regardless, only recommend products or services that we try personally and believe will add value to our readers.