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 cursor.execute(sql) response = cursor.fetchall() # Loop through the response and print table names for row in response: print row
For more examples on how to use MySQLdb in Python, please take a look on Zetcode.com.
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.