快速熟悉python 下使用mysql(MySQLdb)

首先你需要安装上mysql和MySQLdb模块(当然还有其他模块可以用),这里我就略过了,如果遇到问题自行百度(或者评论在下面我可以帮忙看看)

这里简单记录一下自己使用的学习过程:

一、连接数据库

  MySQLdb提供了connect函数,使用如下

  cxn=MySQLdb.Connect(host='localhost',user='root',passwd='',db='samp_db',port=3306)

 

   这里的参数的意义都是很明确的,但是这些参数并不是都是必须的:

    1、host参数表示的是数据库所在地址,默认值是localhost,也就是说本机运行这个参数可以不指定

    2、user、passwd 数据库的用户名和密码,必须存在

    3、db 选择你要操作的数据库名,这个可以稍后指定,非必须

    4、port 端口号,默认值3306

    5、charset 用来指定字符集(默认utf8)

二、操作数据库

  1、某些对象可以直接使用query(但是不推荐使用(所以这里基本略过),即使是使用也一定要先判断是否存在这个属性)

  cxn.query('sql语句')

 

  2、使用cur

  cur=cxn.cursor()

 

  这样我们就能使用cur执行各种操作了,示例代码如下:

1 import MySQLdb
2 cxn=MySQLdb.Connect(host='localhost',user='root',passwd='',db='samp_db',port=3306)
3 cur=cxn.cursor()
4 result=cur.execute('select * from students')
5 for i in cur.fetchall():
6     print i

  这段代码就能返回表students中的所有信息了,也就是你进入mysql输入select * from students之后所显示的内容。这里我就假设大家都了解sql的语句  使用了(不了解的可以去学或者用ORM操作数据库)

  接下来我们演示一下怎么更新表,以怎么向表中插入数据为例:

 1 import MySQLdb
 2 cxn=MySQLdb.Connect(host='localhost',user='root',passwd='',db='samp_db',port=3306)
 3 cur=cxn.cursor()
 4 def showtables(tname):
 5     result=cur.execute('select * from %s'%tname)
 6     for i in cur.fetchall():
 7         print i
 8 showtables('students')
 9 cur.execute("insert into students values(4,'liu4',100)")
10 print 'after insert'
11 showtables('students')

 

  这样我们会可以看待结果:

(1L, 'liu', Decimal('100'))
(2L, 'liu2', Decimal('90'))
(3L, 'liu3', Decimal('98'))
after insert
(1L, 'liu', Decimal('100'))
(2L, 'liu2', Decimal('90'))
(3L, 'liu3', Decimal('98'))
(4L, 'liu4', Decimal('100'))

 

  看似是一摸一样的完成了这项工作,但是这时候我们用终端连上mysql。执行一条select * from students却发现我们插入的那条并没有进去。这是因为  我们还缺少一个commit工作。另外工作完成之后我们需要关闭与数据库的连接,于是更改代码如下

 1 import MySQLdb
 2 cxn=MySQLdb.Connect(host='localhost',user='root',passwd='',db='samp_db',port=3306)
 3 cur=cxn.cursor()
 4 def showtables(tname):
 5     result=cur.execute('select * from %s'%tname)
 6     for i in cur.fetchall():
 7         print i
 8 showtables('students')
 9 cur.execute("insert into students values(4,'liu4',100)")
10 cxn.commit()
11 print 'after insert'
12 showtables('students')
13 cur.close()
14 cxn.close()

三、获取返回值

  上面我们是将查询的结果都存在了一个result变量里的,比呢切返回的都是tuple。但是cursor还有若干方法:来接收返回值

  fetchall(self):接收全部的返回结果行.
  fetchmany(self, size=None):接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据.
  fetchone(self):返回一条结果行.
  scroll(self, value, mode='relative'):移动指针到某一行.如果mode='relative',则表示从当前所在行移动value条,如果mode='absolute',则表示从结果集的  第一行移动value条.

四、批量执行和参数

  使用MySQLdb我们不仅可以执行一条语句,更可以将他与python结合起来,这样我们就可以批量操做了

 1 import MySQLdb
 2 cxn=MySQLdb.Connect(host='localhost',user='root',passwd='',db='samp_db',port=3306)
 3 cur=cxn.cursor()
 4 def showtables(tname):
 5     result=cur.execute('select * from %s'%tname)
 6     for i in cur.fetchall():
 7         print i
 8 showtables('students')
 9 v=[]
10 for i in range(10):
11     v.append((i,'liu'+str(i),98))
12 cur.executemany("insert into students values(%s,%s,%s)",v)
13 cxn.commit()
14 print 'after insert'
15 showtables('students')
16 cur.close()
17 cxn.close()

 

  上面用到了两处参数,第五行和第12行

  另外当执行多个命令要用executemany(op,args)它类似 execute() 和 map() 的结合, 为给定的每一个参数准备并执行一个数据库查询/命令

五、零碎

  上面说过db这个属性可以在连接之后指定,如下:

cxn.select_db('students')

 

posted @ 2014-05-24 00:12  mrbean  阅读(2337)  评论(0编辑  收藏  举报