这是我从another question收到的答案。我只是想知道如何在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
答案 0 :(得分:1)
这应该做:
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
答案 1 :(得分:1)
您需要建立与数据库的连接(如果尚未建立),例如:
connectionString = "..."
Set conn = CreateObject("ADODB.Connection")
conn.open connectionString
This place具有各种数据库后端的连接字符串集合。
建立连接后,您将对数据库运行查询。有几种方法可以做到这一点,例如像这样:
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
根据您的实际数据和要求调整fieldname
,table
和condition
。
使用数据库中的值填充字典,如下所示:
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
因为您无论如何都在查询数据库,所以甚至不必使用字典。您可以disconnect the recordset直接检查用户名:
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