Tuesday, March 30, 2010

[Level 3] Install Python MySQLdb.

When you want to write a Python program to connect to MySQL database,
there is a useful API for Python to connect database, called "MySQLdb".
There are the steps for you to install the package:

1. Download setuptools:
# wget -q http://peak.telecommunity.com/dist/ez_setup.py
# python ez_setup.py

2. Download MySQLdb from SourceForge:

3. Build MySQLdb and install it: (I download MySQLdb version for 1.2.3c1)
# gunzip -c ./MySQL-python-1.2.3c1.tar.gz | tar xvf -
# cd ./MySQL-python-1.2.3c1
# python setup.py build
# python setup.py install

4. Prepare Python script.
import MySQLdb
cxn = MySQLdb.connect(host='localhost', db='test', user='root', passwd='admin123' )

## execute command only

cxn.query("grant all on test.* to 'stanley'@'localhost' identified by 'stanley123'")
cxn.query("drop user 'stanley'@'localhost'")

## query from databas

## no query attribute for cursor
#cur.query("select user,host,password from mysql.user") 

cur = cxn.cursor()
cur.execute("select user,host,password from mysql.user")
for data in cur.fetchall():

5. Run it.
# ./testMySQLdb.py
('root', 'localhost', '')
('root', 'localhost.localdomain', '')
('root', '', '')

Wish this helps.

Stanley Huang