I have a really simple question here, but I just can’t find an answer that solves it.
I have a connection string like this:
SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\DB\DB.mdf;Initial Catalog=DB;Integrated Security=True");
It works, but when I try to use it in a PC that doesn’t have SQL Server Express installed, it just won’t connect. It’ll obviously work if I remove that “\SQLEXPRESS” piece, I know, but I’d prefer not to do it manually on each PC I install the software. I tried to do it by using try-catch, but it’s too slow and I think it isn’t very recommended.
Well, I just want to know how to do it via code. Is there a simple way to do so? Will it solve the problem completely? (I mean, will it certainly work in other editions?)
Thanks in advance! (And sorry for my English)
Just to clarify: A SQL server can be installed as a ‘default’ or a ‘named’ instance. I think by default, express installs as a named instance
This allows a single server machine to run multiple SQL servers
To connect to a default instance you specify the server name or IP and that’s all
To connect to a named instance you specify the server/ip + instance name separated by a backslash.
In your case you are looking to connect to a SQL instance called ‘SQLEXPRESS’ on the local machine. (a dot . means local machine)
You ideally want to install SQL on a server machine and use an application configuration file (App.config) to specify the connection string..
App.config supports a section called ConnectionStrings which you can add your connection string to. Then if you add a reference to System.Configuration to your project you can get hold of the connectionstring using the config manager class:
App.config:
Use in code: