VBA ADODB 查询 Return -1

VBA ADODB Query Return -1

我正在尝试使用 VBA 通过 ADODB 连接到 MS Access 数据库。当我 运行 查询时,我总是得到 -1,它应该是 1。我已经使用 *.uld 测试文件检查了连接,发现正常。 请帮忙。

Private Sub Form_Load()
    Dim sql As String
    Dim recdData As New ADODB.Recordset
    Dim sirb As String
    sirb = "12345"
    sql = "SELECT * FROM sirb_registration WHERE sirb = '" & sirb & "'"
    Set recdData = getResult(sql)
End Sub

Private Function getResult(sql As String) As ADODB.Recordset
    Dim db_conn As New ADODB.Connection
    Dim rs As New ADODB.Recordset
    Set getResult = Nothing
    
    db_conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.16.0;Data Source=" & CStr(DLookup("db_path", "[DB_Path]")) & ";Persist Security Info=False;"
    db_conn.Open
    rs.Open sql, db_conn, adOpenDynamic, adLockOptimistic
    
    Set getResult = rs

    MsgBox getResult.RecordCount
    
    rs.Close
    db_conn.Close
    Set db_conn = Nothing
    Set rs = Nothing
End Function

下面是我的数据库 sirb_registration 样本图像。

下图为查询及查询结果。

根据 Microsoft 的文档 here,即使对于 adOpenDynamic RecordCount 有时也总是 -1:

The cursor type of the Recordset object affects whether the number of records can be determined. The RecordCount property will return -1 for a forward-only cursor; the actual count for a static or keyset cursor; and either -1 or the actual count for a dynamic cursor, depending on the data source.

很遗憾,我没能弄清楚“取决于数据源”的具体含义。

很可能因此您的测试在这里毫无意义。您是否只是尝试从记录集中读取数据?