Tuesday 18 November 2008

MySQL - exploring a database with python and MySQLdb

Here's a script wrote to explore a MySQL database, and report information on all the tables therein.
note - you need python (surely everyone has the python?)
and MySQLdb - which on ubuntu is simply ~apt-get install python-mysqldb

#! /usr/bin/env python
import MySQLdb
#change the following line as neccesary,
db = MySQLdb.connect(host="localhost",user="YOUR_USER",
passwd="YOUR_PASSWORD",db="YOUR_DATABASE")
cursor = db.cursor()
cursor.execute("SHOW TABLES")
result=cursor.fetchall()
for record in result:
print "TABLE '%s'"%record[0]
cursor.execute("DESCRIBE %s"%record[0])
descriptions = cursor.fetchall()
for description in descriptions:
for field in description:
print field,"\t",
print
print "_"*50
cursor.close()
db.close()

No comments: