(作者:瑪瑙河,轉載請註明作者或出處,)
在Windows系統中,用Python指令碼通過ADO來操作資料庫是相當有效率的,你犯不著去找各種各樣的資料庫模組,因為ADO已經為你準備好了一切。有時候一個不太複雜卻用簡單的SQL查詢不能解決的問題,用Python指令碼就能很方便的解決,犯不著開啟某些強大的IDE並建立一個工程(殺雞焉用牛刀!),你所需要的工具,僅notepad或其它簡單的文字編輯器就足夠了。要使用ADO,必須安裝pywin32模組。如果您用的是ActivePython,那麼系統中已經安裝了該模組,否則請先下載並安裝pywin32。下面是通過ADO操作MS SQL Server資料庫的例子:
1#-*- coding: utf-8 -*-
2#以下的例子中假設classmates資料庫中有一個名為classmate的表,該表有三個欄位:name(必要欄位)、Email、address,
3import win32com.client
4
5DSN= r"Provider=SQLOLEDB;UID=xx;PWD=yy@cc;Database=classmates;Server=localhost"
6#Select的例子
7Recordset = win32com.client.Dispatch(r"ADODB.Recordset")
8Recordset.ActiveConnection = DSN
9Recordset.Source = r"SELECT name, Email, address FROM dbo.classmate"
10Recordset.CursorType = 0
11Recordset.CursorLocation = 2
12Recordset.LockType = 1
13Recordset.Open()
14numRows = 0
15while not Recordset.EOF:
16 print r'Name:',Recordset.Fields.Item("name").Value.encode('gbk')
17 if Recordset.Fields.Item("Email").Value != None:
18 print r' EMail:',Recordset.Fields.Item("Email").Value.encode('gbk')
19 if Recordset.Fields.Item("address").Value != None :
20 print r' Address:',Recordset.Fields.Item("address").Value.encode('gbk')
21 numRows+=1
22 Recordset.MoveNext()
23print 'Total Rows:',numRows
24
25#Insert的例子
26CommandInsert = win32com.client.Dispatch(r"ADODB.Command")
27CommandInsert.ActiveConnection = DSN
28CommandInsert.CommandText = r"INSERT INTO dbo.classmate (name, Email, address) VALUES ('xx','abc@xyz.com','ABC Street' ) "
29CommandInsert.CommandType = 1
30CommandInsert.CommandTimeout = 0
31CommandInsert.Prepared = true
32CommandInsert.Execute()
33
34#Update的例子
35CommandUpdate = win32com.client.Dispatch(r"ADODB.Command")
36CommandUpdate.ActiveConnection = DSN
37CommandUpdate.CommandText = r"UPDATE dbo.classmate SET Email='xx@yy.com', address='XX Street' WHERE name='xx' "
38CommandUpdate.CommandType = 1
39CommandUpdate.CommandTimeout = 0
40CommandUpdate.Prepared = true
41CommandUpdate.Execute()
42
43#Delete的例子
44CommandDelete = win32com.client.Dispatch(r"ADODB.Command")
45CommandDelete.ActiveConnection = DSN
46CommandDelete.CommandText = r"DELETE FROM dbo.classmate WHERE name = 'xx'"
47CommandDelete.CommandType = 1
48CommandDelete.CommandTimeout = 0
49CommandDelete.Prepared = true
50CommandDelete.Execute()
51
如果您需要操作Access或其他資料庫,只需修改DSN和相應的SQL語句即可,比如:DSN=r'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=D:\Test.mdb;'
參考:
http://www.ecp.cc/pyado.html
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/ado270/htm/mdmscadoobjmod.asp