经典ASP如何从SQL数据库中提取数据并将其放入数组中

3
在SQL Server 2000中,有一个包含两个字段(每月苹果数量和每月橘子数量,针对两个季节)的简单表(Table1)。我需要使用Classic ASP提取这些字段的值,并填充两个数组。约束条件:这些数组已经由一款外部应用程序定义好了,因为我是Classic ASP的初学者,可能会出错,所以不需要太多修改。
这些数组的定义如下:
Dim m_arrApples, m_arrOranges

我已成功连接到数据库,提取数据并在浏览器中显示(格式为图形)。但是当我需要将其转移至数组(以便被那个现成的应用程序接管并处理它(以图形格式显示)时,我遇到了错误。以下是我的代码:
'Open connection with SQL Server
Dim conn
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "Provider=SQLOLEDB;server=" & NameServer & ";database=" & DataBaseName & ";uid=" & NameUser & ";pwd=" & DataBasePassword & ";" 

'Open table and all records for further processing 
dim strSQL
strSQL = "select * from " & Table1
Set rst = conn.Execute(strSQL)

'Going through the records in the table and try to get values of each field and allocate them to the array
If rst.BOF And rst.EOF Then
    Response.Write "No data"
Else

i=0

Do While (Not rst.EOF)
i=i+1

'The line below confirms that the data extracted from database is displayed in the browser
'in its primary form (not graph), but that means I did it correctly up to this point 
Response.Write rst("Apples") & "/" & rst("Oranges") & "<br>"

m_arrApples(i)= rst("Apples")         ' THE ERROR IS AT THIS LINE. HERE THE SCRIPT IS STOPPED
m_arrOranges(i)= rst("Oranges")

rst.MoveNext
Loop
End If

错误是:
Microsoft VBScript runtime error '800a000d' 
Type mismatch 

任何提示都将不胜感激。

在处理动态数组时,如果要定义新的大小,则需要使用 ReDim Preserve。如果您已经知道数组的大小,请使用定长数组。(例如,如果您知道将有10个值,请使用 Dim m_arrApples(9))。 - user692942
1
是的,它起作用了。谢谢!我应该在哪里给你点赞?我已经很久没有使用stackoverflow了... - Gab2021
并不是你使用了错误的方法来调整数组大小,而是你没有定义任何数组,无论是动态的、固定的还是其他类型的。Lankymart的答案依赖于Redim实际上会将非数组变量转换为数组,但如果你将数组声明为数组,如Dim m_arrApples(),m_arrOranges(),那么你的代码将更容易理解。 - Martha
@Martha,这是老生常谈的争论,差异微小,只要你使用ReDim就无关紧要了。然而,仍有一个强有力的理由使用Dim yourvar(),那就是IsArray()始终为True,而Dim yourvar只是一个变量,因此它将返回False-请参见Dim output() versus Dim output - user692942
@Gab2020 那是一条注释,现在我已经添加了一个答案 - user692942
2个回答

2

0
尝试使用Recordset的Getrows()方法。
'Create a Recordset
Dim objRS
Set objRS = Server.CreateObject("ADODB.Recordset")
objRS.Open "SELECT * FROM Table1", objConn

'now read the Recordset into a 2nd array
Dim aTable1Values
aTable1Values = objRS.GetRows()

你可以通过以下方式遍历这个二维数组:
Dim iRowLoop, iColLoop
For iRowLoop = 0 to UBound(aTable1Values, 2)
  For iColLoop = 0 to UBound(aTable1Values, 1)
    Response.Write(aTable1Values(iColLoop, iRowLoop) & "<br>")
  Next 'iColLoop

  Response.Write("<p>")
Next 'iRowLoop

更多信息请点击这里 https://web.archive.org/web/20210619191820/https://www.4guysfromrolla.com/aspfaqs/ShowFAQ.asp?FAQID=161


这并不会给你两个单维数组,而是一个多维数组,你仍然需要将其拆分成两个数组 - “我需要使用Classic ASP提取这些字段的值,并填充两个数组。约束条件:这些数组已经被定义。” 此外,OP在您发布之前已经发表了评论GetRows()非常好用,但在这种情况下没有任何好处。 - user692942
然而,它会为数组提供大小以帮助重新调整大小。 - Brian T
1
@BrianT:嗯,你知道 objRS.RecordCount 吗? - Martha
@Martha - 可以使用那个,但是你会有一个多的,不是吗?;-) - Brian T

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接