Working with Passwords
In working with passwords, you probably won't want to hard-code the password into your application, because that defeats the purpose of placing a password on your database. In Listing 19.8, the database's password is included in the code, allowing the link to be made to the secured table without any password validation.
Listing 19.8 Embedding a Database Password in Code
Sub LinkToSecured()
Dim cat As ADOX.Catalog
Dim tbl As ADOX.Table
'Instantiate a Catalog object
Set cat = New ADOX.Catalog
'Set the ActiveConnection property of the Catalog
'object to the connection associated with the
'current project
cat.ActiveConnection = CurrentProject.Connection
'Instantiate a Table object
Set tbl = New ADOX.Table
'Set the Name property of the Table object
tbl.Name = "tblLinkedTable"
'Associate the ParentCatalog of the Table object
'with the Catalog object
Set tbl.ParentCatalog = cat
'Set properties of the Table object
tbl.Properties("Jet OLEDB:Create Link") = True
tbl.Properties("Jet OLEDB:Link Provider String") = "ODBC" & _
";DATABASE=Pubs" & _
";UID=SA" & _
";PWD=" & _
";DSN=PublisherData"
tbl.Properties("Jet OLEDB:Remote Table Name") = "Authors"
'Append the Table object to the Tables collection
'associated with the Catalog object
cat.Tables.Append tbl
End Sub
An invalid password results in a message appearing, requiring the user to log on. Unless you are using integrated Windows NT security to log on to your database server, it is best to require the user to supply the password at runtime. In Listing 19.9, the code prompts the user for a password. The password entered by the user is used as part of the connection string.
Listing 19.9 Requiring Password Validation
Sub ReallySecure()
Dim cat As ADOX.Catalog
Dim tbl As ADOX.Table
Dim strPassword As String
'Instantiate a Catalog object
Set cat = New ADOX.Catalog
'Set the ActiveConnection property of the Catalog
'object to the connection associated with the
'current project
cat.ActiveConnection = CurrentProject.Connection
Set tbl = New ADOX.Table
'Set the Name property of the Table object
tbl.Name = "tblLinkedTable"
'Associate the ParentCatalog of the Table object
'with the Catalog object
Set tbl.ParentCatalog = cat
'Prompt the user for the password
strPassword = InputBox("Please Enter Your Password", "Database Security!!!")
'Set properties of the Table object
tbl.Properties("Jet OLEDB:Create Link") = True
tbl.Properties("Jet OLEDB:Link Provider String") = "ODBC" & _
";DATABASE=Pubs" & _
";UID=SA" & _
";PWD=" & strPassword & _
";DSN=PublisherData"
tbl.Properties("Jet OLEDB:Remote Table Name") = "Authors"
'Append the Table object to the Tables collection
'associated with the Catalog object
cat.Tables.Append tbl
End Sub
Notice that the code retrieves the password from the user and stores it in a variable called strPassword. This strPassword variable is included in the connection string at runtime.