问题
this is an answer I received from another question. I was just wondering how I use an SQL Query in asp to add users to the scripting dictionary using a database instead of writing them manually.
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
回答1:
You need to establish a connection to your database (in case it isn't already established), e.g.:
connectionString = "..."
Set conn = CreateObject("ADODB.Connection")
conn.open connectionString
This place has a collection of connection strings for various database backends.
With the connection established you run a query against the database. There are several ways to do this, e.g. like this:
query = "SELECT fieldname FROM table WHERE condition"
Set cmd = CreateObject("ADODB.Command")
cmd.CommandText = query
Set rs = cmd.Execute
or like this:
query = "SELECT fieldname FROM table WHERE condition"
Set rs = CreateObject("ADODB.Recordset")
rs.CursorPosition = 3
rs.open query, conn, 3, 1
Adjust fieldname, table and condition according to your actual data and requirements.
Fill the dictionary with the values from the database like this:
Set bannedUsers = CreateObject("Scripting.Dictionary")
Do Until rs.EOF
bannedUsers.Add rs("fieldname").Value, True
rs.MoveNext
Loop
If the table doesn't have a unique index on fieldname you may want to check the dictionary for the existence of the key before adding it:
If Not bannedUsers.Exists(rs("fieldname").Value) Then
bannedUsers.Add rs("fieldname").Value, True
End If
Since you're querying a database anyway you don't even have to use a dictionary. You could disconnect the recordset and check it directly for user names:
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
回答2:
This should do :
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
来源:https://stackoverflow.com/questions/17117939/use-sql-query-in-asp-to-populate-scripting-dictionary