如何确定 SQL 表中的记录数,然后将该值保存在变量中?
问问题
13330 次
2 回答
1
使用ADO访问数据库:
- 执行一个简单的
SELECT count(0) FROM myTable
查询。 - 访问结果集(如果不为空)并读取返回值。
未测试代码:
Dim conn, rs, recordsCount
recordsCount = -1
'initialize the connection
set conn = ...
'run the query and retrieve the results
set rs = conn.execute("SELECT count(0) as cnt FROM myTable")
if not rs.EOF then
recordsCount = cint(rs("cnt"))
end if
'cleanup
rs.close
conn.close
set rs = nothing
set conn = nothing
于 2012-12-03T17:17:25.610 回答
1
获取查询记录集/结果大小的三种方法:
Option Explicit
' simple way to get a connection
Dim oDb : Set oDb = CreateObject("ADODB.Connection")
oDb.Open "dsn=NWIND"
' execute & !obtain result! of "SELECT COUNT()" query
WScript.Echo "Select Count(*):", oDb.Execute("SELECT COUNT(*) FROM Products").Fields(0).Value
' trying to use recordcount (fails, because non-static rs)
WScript.Echo "RecordCount (A):", oDb.Execute("SELECT * FROM Products").RecordCount
' use recordcount with static rs
Const adOpenStatic = 3
Dim oRs : Set oRS = CreateObject("ADODB.Recordset")
oRS.Open "SELECT * FROM Products", oDb, adOpenStatic
WScript.Echo "RecordCount (B):", oRs.RecordCount
' get rows from query and use UBound()
Dim aData : aData = oDb.Execute("SELECT * FROM Products").GetRows()
WScript.Echo "GetRows():", UBound(aData, 2) + 1
oDb.Close
输出:
cscript 04.vbs
Select Count(*): 77
RecordCount (A): -1
RecordCount (B): 77
GetRows(): 77
使用文档了解有关这些策略的更多信息。
于 2012-12-03T17:42:59.880 回答