How to get the connection String from a database

Pomster picture Pomster · May 7, 2012 · Viewed 389.6k times · Source

I have created a database with SQL Server Management Studio, I would like to now use it in my C# application. I need the connection string?

Where can I find the connection string, and where is my database stored?

Do I have to publish it or something like that, or is it in my documents somewhere?

using (var conn = new SqlConnection("your connection string to the database"))

How do I obtain the connection string? Where can I find the connection string to copy paste into the above section?

How to I publish my database so that Visual Studio can pick it up? Then I can just pull the connection string of there?

Answer

JotaBe picture JotaBe · May 7, 2012

The easiest way to get the connection string is using the "Server Explorer" window in Visual Studio (menu View, Server Explorer) and connect to the server from that window.

Then you can see the connection string in the properties of the connected server (choose the connection and press F4 or Alt+Enter or choose Properties on the right click menu).

Advanced connection string settings: when creating the connection, you can modify any of the advanced connection string options, like MARS, resiliency, timeot, pooling configuration, etc. by clicking on the "Advanced..." button on the bottom of the "Add connection" dialog. You can access this dialog later by right clicking the Data Connection, and choosing "Modify connection...". The available advanced options vary by server type.

If you create the database using SQL Server Management Studio, the database will be created in a server instance, so that, to deploy your application you'll have to make a backup of the database and deploy it in the deployment SQL Server. Alternatively, you can use a data file using SQL Server Express (localDB in SQL Server 2012), that will be easily distributed with your app.

I.e. if it's an ASP.NET app, there's an App_Datafolder. If you right click it you can add a new element, which can be a SQL Server Database. This file will be on that folder, will work with SQL Express, and will be easy to deploy. You need SQL Express / localDB installed on your machine for this to work.