第十三章 Python数据库编程
本章节讲解Python操作数据库,完成简单的增删改查工作,以MySQL数据库为例。 Python的MySQL数据库操作模块叫MySQLdb,需要额外的安装下。 通过pip工具安装:pip install MySQLdb MySQLdb模块,我们主要就用到连接数据库的方法MySQLdb.Connect(),连接上数据库后,再使用一些方法做相应的操作。 MySQLdb.Connect(parameters...)方法提供了以下一些常用的参数: 参数 描述 host 数据库地址 user 数据库用户名, passwd 数据库密码,默认为空 db 数据库库名,没有默认库 port 数据库端口,默认3306 connect_timeout 连接超时时间,秒为单位 use_unicode 结果以unicode字符串返回 charset 插入数据库编码 连接对象返回的connect()函数: commit() 提交事务。对支持事务的数据库和表,如果提交修改操作,不适用这个方法,则不会写到数据库中 rollback() 事务回滚。对支持事务的数据库和表,如果执行此方法,则回滚当前事务。在没有commit()前提下。 cursor([cursorclass]) 创建一个游标对象。所有的sql语句的执行都要在游标对象下进行。MySQL本身不支持游标,MySQLdb模块对其游标进行了仿真。 游标对象也提供了几种方法: close() 关闭游标 execute(sql) 执行sql语句 excutemany(sql) 执行多条sql语句 fetchone() 从执行结果中取第一条记录 fetchmany(n) 从执行结果中取n条记录 fetchall() 从执行结果中取所有记录 scroll(self, value, mode='relative') 游标滚动 博客地址:http://lizhenliang.blog.51cto.com QQ群:323779636(Shell/Python运维开发群) 13.1 数据库增删改查 13.1.1 在test库创建一张user表,并添加一条记录 >>>conn=MySQLdb.Connect(host='192.168.1.244',user='root',passwd='QHyCTajI',db='test',charset='utf8') >>>cursor=conn.cursor() >>>sql="createtableuser(idint,namevarchar(30),passwordvarchar(30))" >>>cursor.execute(sql)#返回的数字是影响的行数 0L >>>sql="insertintouser(id,name,password)values('1','xiaoming','123456')" >>>cursor.execute(sql) 1L >>>conn.commit()#提交事务,写入到数据库 >>>cursor.execute('showtables')#查看创建的表 1L >>>cursor.fetchall()#返回上一个游标执行的所有结果,默认是以元组形式返回 ((u'user',),) >>>cursor.execute('select*fromuser') 1L >>>cursor.fetchall() ((1L,u'xiaoming',u'123456'),) 13.1.2 插入多条数据 >>>sql='insertintouser(id,name,password)values(%s,%s,%s)' >>>args=[('2','zhangsan','123456'),('3','lisi','123456'),('4','wangwu','123456')] >>>cursor.executemany(sql,args) 3L >>>conn.commit() >>>sql='select*fromuser' >>>cursor.execute(sql) 4L >>>cursor.fetchall() ((1L,u'xiaoming',u'123456'),(2L,u'zhangsan',u'123456'),(3L,u'lisi',u'123456'),(4L,u'wangwu',u'123456')) args变量是一个包含多元组的列表,每个元组对应着每条记录。当查询多条记录时,使用此方法,可有效提高插入效率。 13.1.3 删除用户名xiaoming的记录 >>>sql='deletefromuserwherename="xiaoming"' >>>cursor.execute(sql) 1L >>>conn.commit() >>>sql='select*fromuser' >>>cursor.execute(sql) 3L >>>cursor.fetchall() ((2L,u'zhangsan',u'123456'),(3L,u'lisi',u'123456'),(4L,u'wangwu',u'123456')) 13.1.4 查询记录 >>>sql='select*fromuser' >>>cursor.execute(sql) 3L >>>cursor.fetchone()#获取第一条记录 (2L,u'zhangsan',u'123456') >>>sql='select*fromuser' >>>cursor.execute(sql) 3L >>>cursor.fetchmany(2)#获取两条记录 ((2L,u'zhangsan',u'123456'),(3L,u'lisi',u'123456')) 13.1.4 以字典形式返回结果 默认显示是元组形式,要想返回字典形式,使得更易处理,就用到cursor([cursorclass])中的cusorclass参数。 传入MySQLdb.cursors.DictCursor类: >>>cursor=conn.cursor(MySQLdb.cursors.DictCursor) >>>sql='select*fromuser' >>>cursor.execute(sql) 3L >>>cursor.fetchall() ({'password':u'123456','id':2L,'name':u'zhangsan'},{'password':u'123456','id':3L,'name':u'lisi'},{'password':u'123456','id':4L,'name':u'wangwu'}) 13.2 遍历查询结果 #!/usr/bin/envpython #-*-coding:utf-8-*- importMySQLdb try: conn=MySQLdb.Connect(host='127.0.0.1',port=3306,user='root',passwd='123456',connect_timeout=3,charset='utf8') cursor=conn.cursor() sql="select*fromuser" cursor.execute(sql) foriincursor.fetchall(): printi exceptException,e: print("ConnectionError:"+str(e)) finally: conn.close() #pythontest.py (2L,u'zhangsan',u'123456') (3L,u'lisi',u'123456') (4L,u'wangwu',u'123456') 使用for循环遍历查询结果,并增加了异常处理。