您需要建立与数据库的连接(以防尚未建立),例如:
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
调整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
由于您无论如何都在查询数据库,因此您甚至不必使用字典。您可以断开记录集并直接检查用户名:
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