python适合开发数据库编程吗_第十三章 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 = "create table user(id int,name varchar(30),password varchar(30))"

>>> cursor.execute(sql) # 返回的数字是影响的行数

0L

>>> sql = "insert into user(id,name,password) values('1','xiaoming','123456')"

>>> cursor.execute(sql)

1L

>>> conn.commit() # 提交事务,写入到数据库

>>> cursor.execute('show tables') # 查看创建的表

1L

>>> cursor.fetchall() # 返回上一个游标执行的所有结果,默认是以元组形式返回

((u'user',),)

>>> cursor.execute('select * from user')

1L

>>> cursor.fetchall()

((1L, u'xiaoming', u'123456'),)

13.1.2 插入多条数据>>> sql = 'insert into user(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 * from user'

>>> 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 = 'delete from user where name="xiaoming"'

>>> cursor.execute(sql)

1L

>>> conn.commit()

>>> sql = 'select * from user'

>>> 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 * from user'

>>> cursor.execute(sql)

3L

>>> cursor.fetchone() # 获取第一条记录

(2L, u'zhangsan', u'123456')

>>> sql = 'select * from user'

>>> 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 * from user'

>>> 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/env python

# -*- coding: utf-8 -*-

import MySQLdb

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 * from user"

cursor.execute(sql)

for i in cursor.fetchall():

print i

except Exception, e:

print ("Connection Error: " + str(e))

finally:

conn.close()

# python test.py

(2L, u'zhangsan', u'123456')

(3L, u'lisi', u'123456')

(4L, u'wangwu', u'123456')

使用for循环遍历查询结果,并增加了异常处理。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值