只是想知道是否有人看到过这个问题,当尝试将断开连接的记录集中的项目插入到经典的 ASP 字典对象中时,我收到错误“此键已与此集合的元素相关联”。
事实并非如此,所有关键元素都是唯一的,是的,我对数据进行了三次检查:)
如果我将数据推送到局部变量中,它可以正常工作(请参阅下面的代码)。虽然我对此没有意见,但有没有其他人看到过这个问题或知道为什么它不起作用?
Set Options=Server.CreateObject("Scripting.Dictionary")
function Populate(ID) ' WORKS
Dim strsql, rs, name, id
if Options.Count = 0 then
strsql = "select name, ID from options where unique = " & SafeSQL(ID)
Set rs = RunSQLReturnRS(strsql, null, "Populate") ' returns a disconnected recordset
do while not rs.eof
name = rs("name")
id = rs("id")
Options.Add name, id
rs.movenext
loop
rs.close
end if
end function
function Populate2(ID) ' DOES NOT WORK
Dim strsql, rs
if Options.Count = 0 then
strsql = "select name, ID from options where unique = " & SafeSQL(ID)
Set rs = RunSQLReturnRS(strsql, null, "Populate") ' returns a disconnected recordset
do while not rs.eof
Options.Add rs("name"), rs("id")
rs.movenext
loop
rs.close
end if
end function
应用户 Shadow Wizard 的请求,断开记录函数,(注意 my_conn 是数据库连接,在调用该函数时已经打开)
Function RunSQLReturnRS(sqlstmt, params(), fromfunction)
''//Create the ADO objects
Dim rs, cmd
Set rs = server.createobject("ADODB.Recordset")
If Not zerolength(sqlstmt) then
Set cmd = server.createobject("ADODB.Command")
''//Init the ADO objects & the stored proc parameters
cmd.ActiveConnection = my_conn
cmd.CommandText = sqlstmt
cmd.CommandType = adCmdText
cmd.CommandTimeout = 900
''// propietary function that put params in the cmd
collectParams cmd, params
''//Execute the query for readonly
rs.CursorLocation = adUseClient
On Error Resume Next
rs.Open cmd, , adOpenForwardOnly, adLockReadOnly
If Err.Number <> 0 Then Response.write "Error: "&Err.Description & "<br>fromfunction=" & fromfunction & "<br>" : Response.end
On Error Goto 0
''// Disconnect the recordset
Set cmd.ActiveConnection = Nothing
Set cmd = Nothing
Set rs.ActiveConnection = Nothing
End if
''// Return the resultant recordset
Set RunSQLReturnRS = rs
End Function
最佳答案
好吧,这有点棘手,但我知道发生了什么。Add()
VBScript Dictionary 对象的方法正在接受一个对象作为键和值参数。该对象可以是任何类型:数字、字符串、日期、复杂类型等。
不为人知的是,当你写rs("name")
其中 "rs"是 Recordset 类型,它不返回原始类型,而是返回 字段对象 .
但是,如果您尝试将其分配给局部变量,VBScript 足够聪明,可以查找该对象的默认属性,如果存在,则执行它。 Field 对象确实有这样的属性,它返回字段的值。
当你有这个时:
name = rs("name")
它实际上意味着:
name = rs("name").Value
所以在你的第一种方法中,你给一个字符串作为键,一切都很好。在您的第二种方法中,您传递 Field 对象本身,而 VBScript 缺乏 Field 对象之间的适当比较机制,因此它认为它们都是相同的。
要让第二种方法在不使用局部变量的情况下工作,请将其更改为:
do while not rs.eof
Options.Add rs("name").Value, rs("id").Value
rs.movenext
loop
关于asp-classic - 将断开连接的记录集插入字典对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30839108/