(作者:玛瑙河,转载请注明作者或出处,)
在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