ActiveX Data Objects
外观
微软公司的ADO (ActiveX Data Objects) 是一个用于存取数据源的COM组件。它提供了编程语言和统一数据访问方式OLE DB的一个中间层。允许开发人员编写访问数据的代码而不用关心数据库是如何实现的,而只用关心到数据库的连接。访问数据库的时候,关于SQL的知识不是必要的,但是特定数据库支持的SQL命令仍可以通过ADO中的命令对象来执行。
ADO被设计来继承微软早期的数据访问对象层,包括RDO (Remote Data Objects) 和DAO(Data Access Objects)。ADO在1996年冬被发布。
ADO包含一些顶层的对象:
- 连接,代表到数据库的连接
- 记录集,代表数据库记录的一个集合
- 命令,代表一个SQL命令
- 记录,代表数据的一个集合
- 流,代表数据的顺序集合
- 错误,代表数据库访问中产生的意外
- 字段,代表一个数据库字段
- 参数,代表一个SQL参数
- 属性,保存对象的信息
ADO组件的使用需要利用支持COM的高级语言,例如ASP中的VBScript或者Visual Basic,甚至微软的竞争对手Borland的产品Delphi,,现在也支持使用ADO来访问数据库。
在新的编程框架.NET Framework中, 微软也提供了一个面向Internet的版本的ADO,称为ADO.NET。其对象模型和传统ADO差别很大。
基本功能
使用 ADO 存取資料的一些基本步驟 :
- 生成一個連結物件去連結資料庫(Create a connection object to connect to the database.)
- 生成一個recordset物件來取得資料(Create a recordset object in order to receive data in.)
- 開啟一個連結(Open the connection)
- 在recordset中完成SQL語法的描述(Populate the recordset by opening it and passing the desired table name or SQL statement as a parameter to open function.)
- Do all the desired searching/processing on the fetched data.
- 確定改變資料(Commit the changes you made to the data (if any) by using Update or UpdateBatch methods.)
- 關閉recordset(Close the recordset)
- 關閉連結(Close the connection)
ASP 範例
Here is an ASP example using ADO to select the "Name" field, from a table called "Phonebook", where a "PhoneNumber" was equal to "555-5555".
dim myconnection, myrecordset, name
set myconnection = server.createobject("ADODB.Connection")
set myrecordset = server.createobject("ADODB.Recordset")
myconnection.open mydatasource
myrecordset.open "Phonebook", myconnection
myrecordset.find "PhoneNumber = '555-5555'"
name = myrecordset.fields.item("Name")
myrecordset.close
set myrecordset = nothing
set myconnection = nothing
這相當於下列的 ASP code, 以 plain SQL 取代 Recordset object:
dim myconnection, myrecordset, name
set myconnection = server.createobject("ADODB.connection")
myconnection.open mydatasource
set myrecordset = myconnection.execute("SELECT Name FROM Phonebook WHERE PhoneNumber = '555-5555'")
name = myrecordset(0)