python中mysqldb模块_Python学习之MySQLdb模块

CentOS下安装

sudo yum install MySQL-python

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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值