vbscriptsqloledb

vbscript using variables when connecting to databases


I'm trying to use variables to store my username and password for my database in a password-protected program, pass them as parameters, and then use them in a VBScript as arguments that will send the info to the database. This will prevent the user from seeing the username and password that's protecting the database and allow them to tamper with it.

When I have the username and password in the VBScript, it works fine.

strConnect = "PROVIDER=sqloledb.1;Data Source=myDatabase;Initial Catalog=myGroup;User ID=JoeSmith;Password=twinkles324"

But, when I send them as parameters to the VBScript, accept them as arguments, and try to connect, I get the 80040E4D error stating "Login failed for user 'Username'."

Dim Arg, conn, strConnect, Data1, Data2, Data3, Data4
Set Arg = WScript.Arguments
Username = Arg.Item(0)
Pswrd = Arg.Item(1)

Set conn = CreateObject("ADODB.Connection")

strConnect = "PROVIDER=sqloledb.1;Data Source=myDatabase;Initial Catalog=myGroup;User ID=Username;Password=Pswrd"
conn.Open strConnect

strSQL = "INSERT INTO MyTable (Data1, Data2, Data3, Data4)" VALUES ('" & Data1 & "', '" & Data2 & "', '" & Data3 & "', '" & Data4 & "')

conn.Execute strSQL

conn.Close
strSQL = ""

Can anyone help me figure out why I'm not able to use variables to connect to databases?


Solution

  • VBScript isn't going to scan a string literal for variable names. You must put them outside the string literal:

    strConnect = "PROVIDER=sqloledb.1;Data Source=myDatabase;Initial Catalog=myGroup;User ID=" & Username & ";Password=" & Pswrd
    

    Otherwise you're attempting to log in with the literal username &Username