从 ADO Recordset 返回的零行

Zeros rows returned from ADO Recordset

我正在尝试使用以下代码将数据从 SQL 服务器 table 获取到 ADO 记录集中。一切正常,没有错误,但我总是得到 -1 的记录数。我已经确认数据库名称和 table 是正确的。如果我使用 SSMS,我可以看到 table 中有数据。

我在这里错过了什么?

Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim rsCount As Integer

cn.ConnectionString = "Provider=SQLNCLI11;Server=Server1;DataBase=Database1;Trusted_Connection=yes;"
cn.Open

Call rs.Open("Select * from table1", cn, adOpenDynamic, adLockOptimistic)

rsCount = rs.RecordCount

正如我在对该问题的评论中提到的,将 adOpenDynamic 替换为 adOpenStatic 并且您应该获得正确的记录计数。

The use of the ADO Recordset's .RecordCount property requires either the use of:

1. Static or Keyset server-side cursors or
2. A client-side cursor (which returns a Static cursor)

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.

更多详情here and here