MySQLdb记录

MySQLdb API文档

 
 
MySQLdb用于使用python连接MySQL数据库,并进行相关的增删改查各类操作
以下URL为python官网上关于MySQLdb的介绍
在使用MySQLdb之前需要安装MySQLdb,在windows环境下不同版本的python有不同的安装包,且区分32位与64位,我安装的是MySQL-python-1.2.4.win-amd64-py2.6.exe,可通过谷歌搜索或者http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python直接下载;rpm包可通过搜索MySQL-python rpm找到,debian类似
 
与其他语言类似,使用MySQLdb连接MySQL数据库大致也分为以下几个步骤:
  1. 创建连接
  2. 创建游标
  3. 通过游标执行SQL语句
  4. 获取返回结果
  5. 若出现异常,进行相关处理
  6. 关闭游标后,在关闭连接


Connection

__init__(self, *args, **kwargs) 
(Constructor)

Create a connection to the database. It is strongly recommended that you only use keyword parameters. Consult the MySQL C API documentation for more information.
 
通常会使用到的参数有host,user,passwd,db,port,其他参数请参考API
 
 1 以下为一段执行查询SQL语句代码:
 2 import MySQLdb
 3 
 4 
 5 def mysqldbtest():
 6     #create the connettion
 7     conn = MySQLdb.connect(host='192.168.xx.xx' , user='root', passwd=' xxx', db='test' )
 8     #create the cursor
 9     cur = conn.cursor()
10     
11     try:
12         row = cur.execute( 'select * from test')
13          print row
14          print cur.fetchmany( 2)
15          print cur.fetchall()
16          print cur.fetchone()
17     except Exception as e:
18          print e
19     finally:
20         cur.close()
21         conn.close()
22 pass  
23 
24 if __name__ == '__main__':
25     mysqldbtest()
26 
27 
28 
29 以下为一段执行插入SQL语句代码:
30 def mysqldbinserttest():
31     #create the connettion
32     conn = MySQLdb.connect(host='192.168.xx.xx' , user='root', passwd=' xxx', db='test' )
33     #create the cursor
34     cur = conn.cursor()
35     
36     try:
37          from locale import str
38          for i in range( 1, 100):
39             name = 'hello'
40             sql = 'insert into test values("%d","%s")' %(i, name + str(i))
41              print sql
42             cur.execute(sql) 
43         conn.commit()
44     except Exception as e:
45         conn.rollback()
46          print e
47     finally:
48         cur.close()
49         conn.close()
50 pass

 

 
 
posted @ 2013-12-06 11:07  miteng  阅读(194)  评论(0编辑  收藏  举报