CentOS下安装
sudo yum install MySQL-python
可以参考http://www.mikusa.com/python-mysql-docs/index.html 获取更多信息
MySQL-python 为Python提供MySQL驱动程序,主要包括两个部件,_mysql和MySQLdb
连接数据库
In [56]: import MySQLdb
In [57]: db=MySQLdb.connect(host='127.0.0.1',user='xxx',passwd='xxx',db='xxx')
2.创建游标
为了能够在多处使用同一个连接,可以创建一个游标对象
In [60]: cur=db.cursor()
3.执行MySQL查询操作
创建数据库表
In [62]: cur.execute("CREATE TABLE song (id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,title TEXT NOT NULL)")
In [67]: songs=('Purple Haze','All Along the Watch Tower','Foxy Lady')
In [68]: for song in songs:
....: cur.execute("INSERT INTO song(title) VALUES (%s)",song)
....: print "Auto Increment ID: %s" %cur.lastrowid
....:
In [5]: cur.execute("SELECT * FROM song WHERE id = %s or id = %s",(1,2))
In [7]: numrows=cur.execute("SELECT * FROM song")
4.获取查询结果
当执行了任何查询操作后,可以用fetchall()或者fetchone()获取
#/usr/bin/python
import MySQLdb
db=MySQLdb.connect(host='127.0.0.1',user='xxx',passwd='xxx',db='xxx')
cur=db.cursor()
cur.execute("SELECT * FROM account")
rows=cur.fetchall()
for row in rows:
for col in row:
print "%s," %col
print "\n"
In [70]: cur.execute("SELECT * FROM song WHERE id=1")
In [71]: print "ID: %s -- Title: %s" %cur.fetchone()
5.异常处理
import MySQLdb
db=MySQLdb.connect(host='127.0.0.1',user='jialebi',passwd='jialebi123',db='dream_android_game_center')
cur=db.cursor()
try:
cur.execute("SELECT * FROM account")
rows=cur.fetchall()
except MySQLdb.Error,e:
try:
print "MySQL Error [%d] : %s" % (e.args[0],e.args[1])
except IndexError:
print "MySQL Error: %s" % str(e)
for row in rows:
for col in row:
print "%s," %col
print "\n"
6.清理连接
n [74]: cur.close()
In [75]: db.close()