[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.
testMySQLdb.py:
#!/usr/bin/python
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():
  #print(data[0],data[1],data[2])
  print(data[0],data[1])
cxn.close()

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

Wish this helps.

regards,
Stanley Huang

Comments

Popular posts from this blog

[Level 2] Shell Interactive With Zenity Episode 5 -- list

[Level 2] iif in Python