1

这是我从另一个问题收到的答案。我只是想知道如何在 asp 中使用 SQL 查询将用户添加到使用数据库的脚本字典中,而不是手动编写它们。

Set bannedUsers = CreateObject("Scripting.Dictionary")
    bannedUsers.Add "johnsmith", True
    bannedUsers.Add "cmanson", True
    ...

    For Each opt In document.getElementById("frmNew").options
      If opt.selected And bannedUser.Exists(opt.text) Then
        MsgBox "This user is banned."
      End If
    Next
4

2 回答 2

2

您需要建立与数据库的连接(以防尚未建立),例如:

connectionString = "..."
Set conn = CreateObject("ADODB.Connection")
conn.open connectionString

这个地方有一系列用于各种数据库后端的连接字符串。

建立连接后,您可以对数据库运行查询。有几种方法可以做到这一点,例如:

query = "SELECT fieldname FROM table WHERE condition"
Set cmd = CreateObject("ADODB.Command")
cmd.CommandText = query
Set rs = cmd.Execute

或像这样:

query = "SELECT fieldname FROM table WHERE condition"
Set rs = CreateObject("ADODB.Recordset")
rs.CursorPosition = 3
rs.open query, conn, 3, 1

调整fieldnametablecondition根据您的实际数据和要求。

用数据库中的值填充字典,如下所示:

Set bannedUsers = CreateObject("Scripting.Dictionary")
Do Until rs.EOF
  bannedUsers.Add rs("fieldname").Value, True
  rs.MoveNext
Loop

如果表上没有唯一索引,fieldname您可能需要在添加键之前检查字典是否存在键:

If Not bannedUsers.Exists(rs("fieldname").Value) Then
  bannedUsers.Add rs("fieldname").Value, True
End If

由于您无论如何都在查询数据库,因此您甚至不必使用字典。您可以断开记录集并直接检查用户名:

query = "SELECT fieldname FROM table WHERE condition"
Set bannedUsers = CreateObject("ADODB.Recordset")
bannedUsers.CursorPosition = 3
bannedUsers.open query, conn, 3, 1

bannedUsers.ActiveConnection = Nothing  'disconnect recordset

For Each opt In document.getElementById("frmNew").options
  If opt.selected Then
    bannedUsers.Filter = "[fieldname] = '" & opt.text & "'"
    If bannedUser.recordCount > 0 Then
      MsgBox "This user is banned."
    End If
  End If
Next
于 2013-06-15T09:51:07.123 回答
0

这应该这样做:

Set bannedUsersSet = conn.execute "SELECT DISTINCT LOGIN FROM BANNED_USERS /* Here goes your query */"
Set bannedUsers = CreateObject("Scripting.Dictionary")

While not bannedUsersSet.EOF
  bannedUsers(bannedUsersSet("LOGIN")) = True
  bannedUsersSet.MoveNext
WEnd
bannedUsersSet.close
Set bannedUsersSet = Nothing
于 2013-06-14T22:36:15.663 回答