|
数据库的操作在目前的 Python 里面已经变得十分的好用,因为有了一套 API 标准。本文下面就讲讲如何使用这套API。它包括以下部分:
一、模块接口
connect( parameters... )
其中的参数格式如下: dsn 数据源名称
user 用户名(可选)
password 密码(可选)
host 主机名(可选)
database 数据库名(可选)
举个例子: connect(dsn=''myhost:MYDB'',user=''guido'',password=''234$'')
或者 connect(''218.244.20.22'',''username'',''password'',''databasename'')
此标准规定了以下的一些全局变量,
apilevel:
表示 DB-API 的版本,分 1.0 和 2.0 。如果没有定义,则默认为 1.0。
threadsafety:
0 Threads may not share the module. 1 Threads may share the module, but not connections. 2 Threads may share the module and connections. 3 Threads may share the module, connections and cursors.
paramstyle:
用于表示参数的传递方法,分为以下五种: ''qmark'' 问号标识风格. e.g ''... WHERE name=?'' ''numeric'' 数字,占位符风格. e.g ''... WHERE name=:1'' ''named'' 命名风格. e.g ''WHERE name=:name'' ''format'' ANSI C printf风格. e.g ''... WHERE name=%s'' ''pyformat'' Python扩展表示法. e.g ''... WHERE name=%(name)s''
异常类:
StandardError
|__Warning
|__Error
|__InterfaceError
|__DatabaseError
|__DataError
|__OperationalError
|__IntegerityError
|__InternalError
|__ProgrammingError
|__NotSupportedError 二、连接对象
连接对象包含如下方法:
.close() 关闭连接
.commit() 用于事务处理里面的提交操作
.rollback() 用于事务处理里面的回滚操作
.cursor() 获得一个游标
三、游标对象
游标对象包含如下属性和方法:
.description 一个列表(name,type_code,display_size,internal_size,precision,scale,null_ok) 此属性只有在取得了数据之后才有,不然会是null值
.rowcount 表示返回值的行数.如果没有执行executeXXX()方法或者此模块没有实现这个方法,就会返回-1
.callproc(procname[,parameters]) (此为可选方法,应为不是所有的数据库都支持存储过程的)
.close() 关闭游标
.execute(operation[,parameters]) 准备并执行一个数据库操作(包括查询和命令)
.executemany(operation,seq_of_parameters) 准备一个数据库命令,然后根据参数执行多次命令
.fetchone() 返回第一行的查询结果
.fetchmany([size=cursor.arraysize]) 返回指定个多个行的值
.fetchall() 返回所有的查询结果
.arraysize 这个参数值表示fetchmany默认情况之下获取的行数
四、数据类型与定义
定义一些常用的数据类型.但是目前用不到,就先不分析
备注:当然,我们要知道的是,这个只是一个标准,一般来说标准里面定义了的会实现,但还有很多特定的实现,我们也需要去掌握哪些东西,不过如果我们将这些标准的掌握了,那么操作一般的就不会有问题了.
下面给出几个数据库相关的网址:
五、例子
下面举的例子是以MSSQL为样板的,但是换成其他的驱动也一样可以做,这个就和 Perl 的数据库操作十分的类似,可以让我们很方便的实现不同数据库之间的移植工作。
1、查询数据
import MSSQL
db = MSSQL.connect(''SQL Server IP'', ''username'', ''password'', ''db_name'')
c = db.cursor()
sql = ''select top 20 rtrim(ip), rtrim(dns) from detail''
c.execute(sql)
for f in c.fetchall():
print "ip is %s, dns is %s" % (f[0], f[1])
2、插入数据 sql = ''insert into detail values(''192.168.0.1'', ''www.dns.com.cn'')
c.execute(sql)
3、ODBC的一个例子 import dbi, odbc # ODBC modules
import time # standard time module
dbc = odbc.odbc( # open a database connection
''sample/monty/spam'' # ''datasource/user/password''
)
crsr = dbc.cursor() # create a cursor
crsr.execute( # execute some SQL """
SELECT country_id, name, insert_change_date
FROM country
ORDER BY name
"""
)
print ''Column descriptions:'' # show column descriptions
for col in crsr.description:
print '' '', col
result = crsr.fetchall() # fetch the results all at once
print ''\nFirst result row:\n '', result[0] # show first result row
print ''\nDate conversions:'' # play with dbiDate object
date = result[0][-1]
fmt = '' %-25s%-20s''
print fmt % (''standard string:'', str(date))
print fmt % (''seconds since epoch:'', float(date))
timeTuple = time.localtime(date)
print fmt % (''time tuple:'', timeTuple)
print fmt % (''user defined:'', time.strftime(''%d %B %Y'', timeTuple))
-------------------------------output--------------------------------
Column descriptions:
(''country_id'', ''NUMBER'', 12, 10, 10, 0, 0)
(''name'', ''STRING'', 45, 45, 0, 0, 0)
(''insert_change_date'', ''DATE'', 19, 19, 0, 0, 1)
First result row:
(24L, ''ARGENTINA'', <DbiDate object at 7f1c80>)
Date conversions:
standard string: Fri Dec 19 01:51:53 1997
seconds since epoch: 882517913.0
time tuple: (1997, 12, 19, 1, 51, 53, 4, 353, 0)
user defined: 19 December 1997
|