今天學習用Python訪問數據庫,以前用ADO習慣了,所以先找個封裝了ADO的模塊來試試。
adodbapi是用python封裝ADO的數據庫訪問模塊,adodbapi接口完全符合Python
DB-API2.0規範,簡單易用。
以下是自己學習過程中寫的一個例程,使用了查詢、建表、插入數據、執行存儲過程等功能,基本上涵蓋了日常數據庫編程所需的功能。
import adodbapi
class DBTestor:
def __init__(self):
self.conn = None
def __del__(self):
try:
self.conn.close()
except:
pass
def connectDB(self, connectString):
self.conn = adodbapi.connect(connectString)
def closeDB(self):
self.conn.close()
def fielddict(self, cursor):
dict = {}
i = 0
for field in cursor.description:
dict[field[0]] = i
i += 1
return dict
def testCommand(self):
u"測試執行SQL命令,及參數、事務"
cursor = self.conn.cursor()
sql = """if exists (select * from sysobjects where id = object_id(N'Demo_Table') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
Drop Table Demo_Table;
CREATE TABLE Demo_Table (
ID int IDENTITY (1, 1) NOT NULL ,
Name varchar(50) NOT NULL Default('')
PRIMARY KEY CLUSTERED
(
[ID ]
)
);"""
cursor.execute(sql)
sql = """INSERT INTO Demo_Table (Name) VALUES (?);"""
cursor.execute(sql, ("jame",))
sql = """INSERT INTO Demo_Table (Name) VALUES (?);"""
cursor.execute(sql, ("jame2",))
sql = """SELECT @@Identity;"""
cursor.execute(sql)
print "Inserted new record's ID = %s" % cursor.fetchone()[0]
cursor.close()
#默認對數據庫進行修改後必須要提交事務,否則關閉數據庫時會回滾
self.conn.commit()
def testQuery(self):
u"測試查詢功能,通過序號和字段名讀取數據"
cursor = self.conn.cursor()
cursor.execute("SELECT * FROM authors")
try:
fields = self.fielddict(cursor)
row = cursor.fetchone()
while row != None:
print "%s: %s %s" % (row[0], row[fields['au_fname']], row[fields['au_fname']])
row = cursor.fetchone()
finally:
cursor.close()
def testStoreProc(self):
u"測試存儲過程功能"
cursor = self.conn.cursor()
sql = """if exists (select * from sysobjects where id = object_id(N'insert_data_demo') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
Drop Procedure insert_data_demo;"""
cursor.execute(sql)
sql = """CREATE PROCEDURE INSERT_DATA_Demo
@Name varchar(50),
@ID int output
AS
INSERT INTO Demo_Table (Name) VALUES (@Name);
Select @ID = @@Identity;"""
cursor.execute(sql)
(name, id) = cursor.callproc("insert_data_demo", ("tom", 0))
print "Inserted new record's ID = %i" % id
sql = """SELECT * FROM Demo_Table;"""
cursor.execute(sql)
print cursor.fetchall()
cursor.close()
self.conn.commit()
if __name__ == "__main__":
test = DBTestor()
test.connectDB("Provider=SQLOLEDB.1;Persist Security Info=True;Password=;User ID=sa;Initial Catalog=pubs;Data Source=.")
try:
test.testQuery()
test.testCommand()
test.testStoreProc()
finally:
test.closeDB()
程序說明:
1. 因爲源代碼有中文,所以要在第一行加上 #coding=utf-8
2. adodbapi默認在Connection的__init__裏面開啓事務BeginTrans(),然後在close方法裏面回滾事務RollbackTrans()。因此對數據庫進行修改之後要調用Connection.commit()提交事務纔會保存數據。這一點與ADO的默認行爲不一致,需要注意。
3. cursor.fetch*()方法返回的是tuple,只能通過序號讀取字段值,如果要通過字段名訪問數據,需要將字段名映射爲序號。測試代碼裏面的fielddict方法利用cursor.description屬性實現了此映射過程。
總結:
感覺Python DB-API2.0接口使用是很簡單和方便的,只不過接口功能稍弱了點,比如沒有MoveFirst等功能,不能多次遍歷單個結果記錄集,而且不直接支持使用字段名訪問數據,需要做轉換。
參考資料:
1. PEP-0249, Python Database API Specification V 2.0
2. adodbapi 官方網站
3. 數據庫連接字符串大全