Flexible Connection String - sql-server

This connection always fails when I transfer my system to another computer. Whatis the correct code for a connection string that can run on another computer?
Public Sub connect()
con = New SqlConnection("data source=.\SQLEXPRESS; Integrated Security=true; User Id=sa;Password=sa;")
con.Open()
End Sub
I'm expecting for the code that can be run on other PC when I transfer my system

That connection string will work on any machine that has a local instance of SQL Server Express with the default name. There's no way to build a connection string that will magically work with any SQL Server instance with any name on any machine. If each user may need a different instance name then you have to provide for that.
One option is to store your connection string in the config file and let each user edit that by hand. That's risky if your user's aren't technically inclined though. You can also store the connection string attribute values somewhere, e.g. My.Settings and then provide a UI for the user to specify them at run time and persist them for later use. The specifics of that are up to you but you can find an example here:
http://www.vbforums.com/showthread.php?532768
The point of that thread was the encryption part but you can ignore that and just use the rest.

Related

SSIS: Configuration of Dynamic Connection String Integrated Security Mode

Setup
In the local environments, we're using SQL Authentication with Username and Password to connect to the databases. I created a Project Connection Manager that has expressions bound to Project Properties, Username and Password being set to sensitive.
On the dev server, when the SSIS run, it needs to use an AD account. I might need to create a Credential/Proxy for the SQL Agent, but for now I'm logged in as the user and I execute the packag through SQL.
Problem
In the SSIS project itself, I'm trying to configure a dynamic connection string to use Integrated Security in one case, and SQL Account in another. I just can't figure out how to do it. Things I tried:
1- Created a boolean "UseIntegratedSecurity" parameter. In the connection string, use that bool to set IntegratedSecurity=SSPI or not with the expression, and also use expressions to set the other attributes of the connection string individually. It didn't work, said the connection string could not be built.
2- Created a boolean "UseIntegratedSecurity" parameter, and write my connection string as something (ugly) like: #[$Project::IntegratedSecurity] ? "Data Source="+#[$Project::SqlServerName]+";Initial Catalog="+#[$Project::SqlServerDatabase]+";Provider=SQLNCLI11.1;Auto Translate=False;Integrated Security=SSPI;" : "Data Source="+#[$Project::SqlServerName]+";Initial Catalog="+#[$Project::SqlServerDatabase]+";Provider=SQLNCLI11.1;Auto Translate=False;User ID="+#[$Project::SqlServerUsername]+";Password=" + #[$Project::SqlServerPassword]
It didn't work because since SqlServerUserName and SqlServerPassword are sensitive, it refuses.
3- Tried having Project Parameters for ConnectionString, Server, Database, User, Password and setting them all. Works locally, but on the server, I get "Invalid Authorization Specifications".
Ideas?
Thanks
You need to handle situation when in one environment you have to use SQL Authentication, and on the other - AD Authentication.
This can be done with help of SSIS Catalog Environment variables. When you create a Project file, Visual Studio automatically creates the following so called project connection parameters for each OLEDB connection manager :
CM.< conn manager name >.ConnectionString
CM.< conn manager name >.InitialCatalog
CM.< conn manager name >.Password Created as sensitive param
CM.< conn manager name >.ServerName
CM.< conn manager name >.UserName
OLEDB is an example, SSIS creates similar parameters for other connection manager types.
Important fact, you do not have to create additional project parameters. The parameters mentioned are created on project being built and are present on all projects.
We create environment variables which specify connection string, DB name (initial catalog), Server Name etc. Good thing - Connection string variable is applied first, and then amended with the other variables.
More details on these parameters is in MS Docs.
In case similar to yours, in Dev environment - using SQL Auth define Conn string for SQL Auth and specify username and password in corresponding variables. In QA env where SSPI is used - the Connection string is reworked for SSPI, UserName and Password environment variables are empty.

Program won't connect to SQL Server

Update: This is fixed thanks to some great help here. If you're having similar issues do the following:
Enable ALL exceptions before running
Figure out the exact error you're getting when trying to connect
Make sure that all users on SQL side have a user assigned to a login for that specific database
I've got a very nice program I've made that I'm ready to start pushing out for testing. The problem is that when I coded all of this I simply used the Integrated Security which uses my windows login to connect to the SQL Server. That worked fine as I'm a sysadmin on that whole server, including the database in question.
Now I'm ready to push this out to other users and I need to change the code to either use my login for all users (hard coded to the connection string) or use a new login specifically for that database.
I've used the following connection string and it won't work! I've also added the server to the data connections section of the server explorer but I guess I don't know how to tell the program to use that connection in my code.
I've obfuscated the password in the code below but it's written out in my code. No errors or anything when running - it just doesn't connect or pull data.
Thoughts? Thanks!
Dim strSQLConn As String = ("Server=Hertz1455;Database=AbsenceApplication;User ID=hac0421;Password=********")
Update - hertz1455 is the server name, there isn't a port that I need to use. Below is the rest of the code for when the program starts. I've also commented on some answers with the error I'm getting.
Dim strSQLConn As String = "Fleet_PTO.My.MySettings.AbsenceApplicationConnectionString"
Dim strQuery As String
Dim sqlSQLCon As SqlConnection
sqlSQLCon = New SqlConnection(strSQLConn)
Dim cmd As SqlCommand = New SqlCommand("SELECT person FROM tblSupervisor", sqlSQLCon)
sqlSQLCon.Open()
Dim myDA As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim myDataTable As DataTable = New DataTable
myDA.Fill(myDataTable)
sqlSQLCon.Close()
When I change the strSqlConn to the string below, everything works just fine.
Dim strSQLConn As String = ("Data Source=Hertz1455;Initial Catalog=AbsenceApplication;Integrated Security=True")
We can only guess since the question is a bit unclear without any exceptions or warning messages.
Try this:
Create a new text file anywhere. (say Desktop)
Rename the extension to udl and open the file.
You should be seeing window.
Test your connection, see if you can connect.
Lat94 might be correct with the Server=Hertz:1455 part although it's not the default MSSQL port.
Also check your server's firewall, it might be blocking the connection request. You might be getting an exception (like connection forcefully rejected) but it might not be popping up. Check exception settings, enable everything since you find a relative clue.
Note:
Dear future viewer, please follow the comments.
Perhaps you should add the driver you're using in order to get it done, like:
Dim strSQLConn As String = ("Server=SQLOLEDB;Server=Hertz1455;Database=AbsenceApplication;User ID=hac0421;Password=********")
Is "1455 at Server=Hertz1455 the port number? Shouldn't it be Server=Hertz:1455 in that case?
Check this link for more info. It is in C#, but it will not be a problem.

How to connect to simple database table?

I don't know much about databases - Sorry if the question seems silly.
I have sql server 2012 on my machine and i create simple database table.
I want to connect to this database table thru C# code.
So, I need to know my ConnectionString.
I don't understand the parameters of the ConnectionString.
I try to google it - but still didn't find any good explanation.
Anyone can please explain the connectionString fields ?
How to define the connectionString that i will be able to connect the local database ?
thanks
Your connection string should be as simple as like below
Data Source=.;Initial Catalog=DB_NAME;Integrated Security=True"
Where
Data Source=. means local database
Initial Catalog=DB_NAME means the database it will connect to
Integrated Security=True means it will use windows authentication (no user name and password needed; it will use logged in credential)
Take a look Here
(OR)
Search in Google with key term sqlconncectionstring which will fetch you many help.
EDIT:
You are getting exception cause Initial Catalog=DB_Name\Table_001. It should be Initial Catalog=DB_Name (only database name). Provide the table name in sql query to execute. Check some online tutorial to get more idea on the same.
You use . in data source only when you are connecting to local machine database and to the default SQL Server instance. Else if you are using different server and named SQL Server instance then your connection string should look like
using(SqlConnection sqlConnection = new SqlConnection())
{
sqlConnection.ConnectionString =
#"Data Source=Actual_server_name\actual_sqlserver_instance_name;
Initial Catalog=actual_database_name_Name;
Integrated Security=True;";
sqlConnection.Open();
}
In case you are using local machine but named SQL Server instance then use
Data Source=.\actual_sqlserver_instance_name;
Initial Catalog=Actual_Database_NAME;Integrated Security=True"
using System.Data.SqlClient;
Then create a SqlConnection and specifying the connection string.
SqlConnection myConnection = new SqlConnection("user id=username;" +
"password=password;server=serverurl;" +
"Trusted_Connection=yes;" +
"database=database; " +
"connection timeout=30");
Note: line break in connection string is for formatting purposes only
SqlConnection.ConnectionString
The connection string is simply a compilation of options and values to specify how and what to connect to. Upon investigating the Visual Studio .NET help files I discovered that several fields had multiple names that worked the same, like Password and Pwd work interchangeably.
User ID
The User ID is used when you are using SQL Authentication. In my experience this is ignored when using a Trusted_Connection, or Windows Authentication. If the username is associated with a password Password or Pwd will be used.
"user id=userid;"
Password or Pwd
The password field is to be used with the User ID, it just wouldn't make sense to log in without a username, just a password. Both Password and Pwd are completely interchangeable.
"Password=validpassword;"-or-
"Pwd=validpassword;"
Data Source or Server or Address or Addr or Network Address
Upon looking in the MSDN documentation I found that there are several ways to specify the network address. The documentation mentions no differences between them and they appear to be interchangeable. The address is an valid network address, for brevity I am only using the localhost address in the examples.
"Data Source=localhost;"
-or-
"Server=localhost;"
-or-
"Address=localhost;"-or-"Addr=localhost;"
-or-"Network Address=localhost;"
Integrated Sercurity or Trusted_Connection
Integrated Security and Trusted_Connection are used to specify wheter the connnection is secure, such as Windows Authentication or SSPI. The recognized values are true, false, and sspi. According to the MSDN documentation sspi is equivalent to true. Note: I do not know how SSPI works, or affects the connection.
Connect Timeout or Connection Timeout
These specify the time, in seconds, to wait for the server to respond before generating an error. The default value is 15 (seconds).
"Connect Timeout=10;"-or-
"Connection Timeout=10;"
Initial Catalog or Database
Initial Catalog and Database are simply two ways of selecting the database associated with the connection.
"Inital Catalog=main;"
-or-
"Database=main;"

Multiple ports listed in SQL Server connection string

I have a legacy VB6 app where the servername, databasename, username, etc are defined in an INI file, but the port number for the connection string (the default 1433) is hard coded in the app. It's being moved to a new sql server back end that runs off a different port number. I'm trying to avoid having to alter and recompile the application which entails signifigant retesting, documentation, etc. I tried altering the INI file so that for the new server I have put in: SERVERNAME\INSTANCE,NEWPORTNUMBER
This effectively builds the connection with Data Source = SERVERNAME\INSTANCE,NEWPORTNUMBER,1433;
This appears to work correctly as it connects to the database when I run the app. It appears to me that the ,1433 portion is being ignored. Is this a valid assumption or will this cause me some problem I'm not seeing here?
EDIT: The string way the connection string is built in the VB6 code is:
ConnectString = "Provider=MSDataShape;Trusted_Connection=Yes;Data Source=" & SERVER & ",1433;Initial Catalog=" & DATABASE & ";Data Provider=SQLOLEDB.1;Extended Properties=""Network=DBMSSOCN"""
with the SERVER & DATABASE values pulled from the INI file.
Port 1433 would normally override the INSTANCENAME. (MS blog Reference and another)
3 options I see:
The instance name is being ignored, and you're connecting to the default instance on port 1433
The named instance listens on port 1433
You have a client alias (not convinced about this one)
Can we see the code that creates the connection string?
Is there a network reason you need to use TCP/IP to connect to sql server?
My guess is that you just need to include a ; after the servername/instance name and just leave the port number out altogether. This will cause the port number to be extraneous data in the connection string. Which I think is just ignored. You can test creating an connection string yourself by creating a test.udl file and double clicking it - follow the wizard. After your done the connection string is in the udl file which you can view with notepad.
And of course if you are looking for the syntax for connection strings, you can look them up on connectionstrings.com
Download a free HEX editor
Save a copy of your original exe somewhere
safe
Open the exe in the HEX editor
Find the 1433 and change it to your
new port number
Once it works, you don't have to retest everything (like you would on a recompile)
If the new port number is not four digits it is trickier (path of least resistance: change it to a four digit port)
I have changed connection strings this way in the past.
A VB6 exe always uses DBCS so you may have to play with the hex editor until you figure out how to use the search feature in the right way.
If the port number is stored as an integer it may be trickier to find, but still possible (look for strings near it for your clues).
Apparently this app is quickly hacked together. Try to hack it back with a simple connect-string-injection like SERVER="{your_server},{your_port};FooBar="
I'm not sure that every library that uses the connection string would necessarily parse it the same way. I would think there could be one library that parses that connection string and just drops off the last port number and another that throws an error for an invalid port number perhaps. What libraries are using that connection string?
If you're using integrated security, then maybe you could set the Data Source in the INI file to say,
SERVERNAME,PORT; Password=
and let the SQL server ignore the Password key, which is unused with integrated security. That is if the code that constructs the connection string doesn't check for stuff like that. Oh, Will Rickards said this already also it seems.

How to connect to other system Database?

Using VB6 and SQL Server 2005
I want to write a sql connection for connecting to other system sql server.
Code
ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI; Persist Security Info=False;Initial Catalog=STAR;Data Source=" & SName & ""
In SName - Am giving a Server Name
The Above connection code is working for the same system, Suppose I want to connect to other system database means
For example
I run the program in system A, the Database in system B. How to write a sql connection
Is possible with IP Address like SName = 192.12.12.1/System B
How to Write a connection string.
Need Code Help.
It depends on your network / DNS, you should be able to enter the machine name, you may also need a domain name.
SQL Server also has something called Named Pipes for accessing a SQL instance by it's name - do a google search on that...
Yes, you can use an IP address or a machine name but not both. The exact syntax is
Data Source=192.12.12.1; Initial Catalog=STAR; User Id=abc; Password=def;
In case, you have a trust established between the two servers, then you can replace the User Id and Password part by using Integrated Security=True just like you are doing if the database and program exist on the same machine.
Various types of connection strings are discussed here: http://connectionstrings.com/sql-server-2005

Resources