日期:2010-05-10 浏览次数:20998 次
现在我们开始写组件中的方法
1、 OpenDB方法
OpenDB方法的思路是建立与MS SQL SERVER7.0的连接,这可以使用SQLOLEDB Provider来实现。建立连接后就可以创建一个包含所有CD信息的记录集。根据以上分析我们写出如下代码。
Option Explicit
Private Conn As ADODB.Connection
Private RecordSetCD As ADODB.Recordset
’打开连接和结果集
Private Sub OpenDB()
Set Conn = New ADODB.Connection
Set RecordSetCD = New ADODB.Recordset
Conn.Open "Provider=SQLOLEDB;DataSource=MUSE;Initial Catalog=Music;UserId=Wayne;Password=AbCdEfG"
RecordSetCD.Open "SELECT * FROM CD", Conn
End Sub
2、 CloseDB方法
由于连接数据库是相当昂贵的,所以在不需要使用数据库时,一定要记住关闭Recordset 和Connection对象,CloseDB就是完成这一操作。
Private Sub CloseDB()
’关闭结果集RecordSetCD
If Not (RecordSetCD Is Nothing) Then
If RecordSetCD.State = adStateOpen Then
RecordSetCD.Close
End If
Set RecordSetCD = Nothing
End If
’关闭连接Conn
If Not (Conn Is Nothing) Then
Conn.Close
Set Conn = Nothing
End If
End Sub
3、 Add方法
Add方法的目的是向数据库中添加一条新的CD信息,因此它打开的记录集要求能够更新。这就不能像OpenDB中那样仅用Open打开数据集。详细的代码见下面:
Private Sub Add(Id As String, Name As String, Author As String, Price As Currency, Information As String)
Dim NewConn As New ADODB.Connection
Dim NewRecordsetCD As New ADODB.Recordset
NewConn.Open "Provider=SQLOLEDB;DataSource=MUSE;Initial Catalog=Music;UserId=Wayne;Password=AbCdEfG"
NewRecordsetCD.Open "SELECT * FROM CD", NewConn, adOpenDynamic, adLockOptimistic
NewRecordsetCD.AddNew
NewRecordsetCD.Fields("CD_ID") = Id
NewRecordsetCD.Fields("CD_Name") = Name
NewRecordsetCD.Fields("CD_Author") = Author
NewRecordsetCD.Fields("CD_Price") = Price
NewRecordsetCD.Fields("CD_Information") = Information
NewRecordsetCD.Update
End Sub
解释:使用 NewRecordsetCD.AddNew,
NewRecordsetCD.Fields(“Some_Key”)=Some_Value
NewRecordsetCD.Update 来添加一条纪录
4、 Delete方法:
这个方法的目的是为了删除库中的某条CD名和相关的信息。它的