循环记录集并添加到字典/集合:项目键存在
Posted
技术标签:
【中文标题】循环记录集并添加到字典/集合:项目键存在【英文标题】:loop a recordset and add to Dictionary/Collection: item key exists 【发布时间】:2018-10-21 18:45:17 【问题描述】:第一个 vba/access 项目,由于某种原因,我似乎无法通过循环将项目添加到集合或字典中:
Dim current_stock As Scripting.Dictionary
Set current_stock = New Scripting.Dictionary
current_stocks_sql = "SELECT id, size,stock FROM bags"
Set rs = db.OpenRecordset(current_stocks_sql)
' On Error Resume Next
Do While Not rs.EOF
current_stock.add rs!id, rs!stock
MsgBox rs!id ' gives 1,2,3 correctly
rs.MoveNext
Loop
'On Error GoTo 0
rs.Close
当它到达 id 2 时,它给出错误项 key 已经存在。
【问题讨论】:
【参考方案1】:Dictionary.Add
允许您将对象存储为键。
Dictionary.Add rs!id, rs!stock
不会将两个值添加到字典中,而是添加两个字段对象,ID 字段和股票字段。
移动到下一条记录后,字段对象仍然相同,因此您会收到 Item key has been exists 错误。
添加值而不是字段对象:
current_stock.add rs!id.Value, rs!stock.Value
【讨论】:
【参考方案2】:对于任何来到此页面的人都在寻找一个基本上可以将记录集转换为字典集合的功能。这是一个函数
Function sql_results(ByVal q As String) As Collection
Dim myConn As New ADODB.Connection
Set myConn = db_conn() ' this is a custom function of mine that connects to ' my database
Dim rs As ADODB.Recordset
Set rs = myConn.Execute(q)
Dim coll As New Collection
Dim dic As New Dictionary
Do Until rs.EOF ' looping through the record set (the rows that are returned ' from the query
Set dic = New Dictionary
For Each Field In rs.Fields ' field = column
dic.Add Field.Name, Field.value ' every column has a name, every 'field has a value
Next Field ' next column
coll.Add dic
rs.MoveNext 'next row
Loop
Set sql_results = coll
End Function
如果有人需要更多说明,请随时发表评论,或者如果您知道某个页面更需要此答案,请链接它。
*免责声明,理想情况下,如果您有一个大型数据集,将其转换为集合字典将不是最明智的内存管理操作
【讨论】:
以上是关于循环记录集并添加到字典/集合:项目键存在的主要内容,如果未能解决你的问题,请参考以下文章