'传递参数SQL传递查询语句,MsgString传递查询信息。自身以一个数据集对象的形式返回
Public Function ExecuteSQL(ByVal SQL As String, MsgString As String) As ADODB.Recordset
Dim Cnn As ADODB.Connection '定义连接
Dim Rst As ADODB.Recordset
Dim sTokens() As String '定义字符串
On Error GoTo ExecuteSQL_Error '异常处理
sTokens = Split(SQL) '用Split函数产生一个包含各个子串的数组
Set Cnn = New ADODB.Connection '创建连接
Cnn.Open ConnectString
If InStr("INSERT,DELETE,UPDATE", UCase$(sTokens(0)))
Then '判断字符串中是否含有指定内容
Cnn.Execute SQL '执行查询语句
MsgString = sTokens(0) & "query successful" '返回查询信息
Else
Set Rst = New ADODB.Recordset '闯将数据集对象
Rst.Open Trim$(SQL), Cnn, adOpenKeyset, adLockOptimistic '返回查询结果
Set ExecuteSQL = Rst '返回记录集对象
MsgString = "查询到" & Rst.RecordCount & " 条记录"
End If
ExecuteSQL_Exit:
Set Rst = Nothing '清空数据集对象
Set Cnn = Nothing '中断连接
Exit Function
ExecuteSQL_Error: '判断错误类型
MsgString = "查询错误:" & Err.Description
MsgBox MsgString
Resume ExecuteSQL_Exit