Search code examples
vbscriptscom

Using VBScript parameters in a connection string


I'm using a vbs script to query SQL Servers.

And in the connection string, i'm trying transfer the following parameters: Server Name (PKNSQLEXP07\SQLINST7) and Port Number (2890).

Problem is, that i know that parameters in VBScript need to be outside the connection string, but i'm not sure how to accomplish that.

This is my connection string, without the parameters:

strConnection = "Driver={SQL Server};Server=PKNSQLEXP07\SQLINST7,2890;Database=master;Trusted_Connection=TRUE"

And this is with Parameters:

    ConnectionString = Wscript.Arguments(0)
TcpPort = Wscript.Arguments(1)

strConnection = "Driver={SQL Server};Database=master;Trusted_Connection=TRUE;Server=" & ConnectionString &,& TcpPort
objCN.Open strConnection

The parameters (ConnectionString and TcpPort) should be with a comma sign between them.

But i have no luck so far, with my current connection string with the parameters.


Solution

  • You are concatenating together strings to make a big string. You have two types of strings.

    1. Strings in variables that you DO NOT want to quote otherwise they will be treated like...
    2. String Literals, which are just strings in quotes like "Hi, I'm a string".

    You are very close with your attempt, but your comma is a String Literal, which means that thing needs to be in quotes:

    strConnection = "Driver={SQL Server};Database=master;Trusted_Connection=TRUE;Server=" & ConnectionString & "," & TcpPort
    

    As a debugging step you can use MsgBox strConnection to see the string that is derived from this concatenation before firing it off to the database. That should give you a lot of insight into what's going on in that line.