數據庫的操作在現在的Python里面已經變得十分的好用,有了一套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默認情況之下獲取的行數

數據類型與定義

定義一些常用的數據類型.但是目前用不到,就先不分析

備注

當然,我們要知道的是,這個只是一個標準,一般來說標準里面定義了的會實現,但還有很多特定的實現,我們也需要去掌握哪些東西,不過如果我們將這些標準的掌握了,那么操作一般的就不會有問題了.

下面給出幾個數據庫相關的網址

Database Topic Guide
Python的數據庫使用向導,有相當不錯的資料,包括API定義,驅動聯結等等
MSSQL 驅動
就是MSSQL的驅動程序

例子

下面舉的例子是以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