一、db-api概述
python支持很多不同的数据库。由于不同的卖家服务器导致和数据库通信的网络协议各有不同。在python的早期版本中,每一种数据库都带有自己的python模块,所有这些模块以不同的方式工作,并提供不同的函数。这种方法不便于编写能够在多种数据库服务器类型中运行的代码,于是db-api库函数产生。在db-api中,所有连接数据库的模块即便是底层网络协议不同,也会提供一个共同的接口。这一点和java中的jdbc和odbc类似。
db-api下载地址:,目前版本是,支持数据库包括ibm db2、firebird (and interbase) 、informix、ingres、mysql、oracle 、postgresql 、sap db (also known as "maxdb") 、microsoft sql server 、sybase 等。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
二、数据库连接
1、postgresql文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
有几个模块可以完成python与postgresql的联接,这里主要介绍使用psycopg。
下载地址是:。如果没有postgresql,可以从以下地址下载:。(关于postgresql的安装等更加详细的介绍,可以见。)连接postgresql数据库:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
import psycopg2
print "connecting to test"##test为数据库名
dbh=('dbname=test user=postgres')
print "connection successful"文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
2、mysql文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
对于mysql,python的接口是已知的mysqldb或者mysql-python,下载地址:。与postgresql不同的是,mysqldb connect()函数可以带各种参数,具体如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
参数 | 说明 |
user | 用户名,默认为当前登录用户。 |
passwd | 用户密码,没有默认的。 |
db | 连接的数据库名。 |
host | 数据库主机名。 |
port | tcp端口,默认是3306。 |
举例,连接test数据库:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
import mysqldb
print "connecting..."
dbh=(db="test")
print "connection successful."
()文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
三、简单操作(以postgresql为例)
这里以postgresql为例介绍创建表、查询表等操作。例子中数据库名为test,用户名为postgres,输入一个表名,向表中插入数据并进行查询。具体如下,已进行了注示:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
import psycopg2
print "connecting to test"
dbh=('dbname=test user=postgres')
print "connection successful"
cur=()#建立一个cursor对象,返回数据为字典形式
a=raw_input('table list:')#输入表名
("create table %s(myid integer unique,filename varchar(255))" %a)#生成表,包含一个字段filename
b=1c='201210310540'
("insert into %s values (%d,%s)"%(a,b,c))#向表中插入记录b,c
("select * from %s " %a)#查询表中内容
rows=()#获得结果集中的所有行
for row in rows:
print row
()#以上对数据库的操作事务生效
()文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
1、事务文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
多数数据库支持事务,事务可以将多条对数据库的改动放在一条命令中。在上面的例子中,当未曾执行commit()命令时,以上对数据库的操作均不会生效。另外还有一个函数rollback(),这个函数可以有效的放弃上一次执行commit()或者rollback()之后的改动。这个函数在发现错误,并想放弃已经发出的事务时,非常有效。对于不支持事务的数据库,改变会立刻执行,commit()什么也不做,但rollback()会报错。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
2、效率文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
执行事件的性能很大程序上取决于不同的服务器,一般来说,在每个单独的命令后都提交是更新数据库最慢的方法,但如果一次提交很大数据又会使服务器产生buffer溢出。因此,应该合理处理提交的数量。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
四、参数风格
在上面的例子中,使用了printf()一样的类型格式。但实际上,在db-api中,不同的数据库所支持的参数风络不同,必须选择合适的方法,否则程序不会执行。下面的方法,可以知道当前所支持的类型格式。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
>>> import psycopg2
>>> print psycopg2.paramstyle文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
pyformat这一结果可以看出,当前支持pyformat格式。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
针对db-api说明书,以使用频度由小变大的顺序介绍:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
qmark | 表示question-mark风格。指令字符串中的数据的每一位都被用一个问号替换,参数以list或tuple的形式给出。例如:insert into ch14 values (?, ?)。 |
format | 使用和printf()一样的类型格式,不支持对于指定参数python的扩展名。它带一个list或tuple来转换。例如:insert into ch14 values(%d, %s) |
numeric | 表示numeric风格。指令字符串中的数据的每一位都被一个后面是数字的冒号替换(数字以1开始),参数以list或tuple的形式给出。例如:insert into ch14 values(:1, :2) |
named | 表示named风格。和numeric类似,但是在冒号后面用名称取代数字。带一个dictionary用来转换。例如:insert into ch14 values(:number, :text) |
pyformat | 支持python风格的参数,带dictionary用来转换。例如:insert into ch14 values(%(number)d, %(text)s)。 |
五、重复指令文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
1、execute和executemany()文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
例子:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
将下面的数据插入到test数据库中:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
12 twelve
13 thirteen
14 fourteen
15 fifteen文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
(1)execute一条条插入文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
("insert into test values (12, 'twelve')")
("insert into test values (13, 'thirteen')")
("insert into test values (14, 'fourteen')")
("insert into test values (15, 'fifteen')")文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
这种方法过于低效。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
(2)executemany()函数带一个指令和一列指令运行的记录。列表上的每条记录要么是一个list,要么是一个dictionary。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
import psycopg2
print "connecting to test"
dbh=('dbname=test user=postgres')
print "connection successful"
cur=()
rows = ({'num': 0, 'text': 'zero'},
{'num': 1, 'text': 'item one'},
{'num': 2, 'text': 'item two'},
{'num': 3, 'text': 'three'})
many("insert into test values (%(num)d, %(text)s)", rows)
()
()文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
executemany()主要的缺点是,在需要执行指令前把所有的记录放在内存中。如果数据大的话,这就是一个问题,它会占有系统的所有内存资源。如果executemany()不能满足需要,那么除了execute()之外,还是有可能取得性能优化的。根据db-api说明,当execute()被周期性调用时,数据库后端可以执行优化。但是它的第一个参数必须指向同一个对象,而不是一个含有相同值的字符串,即在内存中的同一个字符串对象。和executemany()一样,这样并不能保证优化,并且也不能期望execute()运行得比executemany()快。但是如果不能使用executemany(),这就是一个最好的选择。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
六、fetchall、fetchmany、fetchone获取数据文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
fetchall(self):接收全部的返回结果行。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
fetchmany(self, size=none):接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回条数据。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
fetchone(self):返回一条结果行。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
七、获取metadata(元数据)文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
元数据的英文名称是“metadata",它是“关于数据的数据”。如在上面的例子中,metadata的结果为:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
column(name='id', type_code=23, display_size=none, internal_size=4, precision=none, scale=none, null_ok=none)
column(name='filename', type_code=1043, display_size=none, internal_size=255, precision=none, scale=none, null_ok=none)文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
import psycopg2文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
print "connecting to bbstime"文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
dbh=('dbname=bbstime user=postgres')文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
print "connection successful"文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
cur=()文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
("select * from asd")文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
for column in cur.description:
print column文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
()文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
八、计算行数
方法有两种,一种是用len(),一种是用rowcount。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html
import psycopg2
print "connecting to bbstime"
dbh=('dbname=bbstime user=postgres')
print "connection successful"
cur=()
("select * from test")
rows=()
print len(rows)#利用len来计算行数
print "rows:",利用rowcount来计算行数文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/10804.html