332

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?

1

11 Answers 11

296

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.

9
  • 2
    I understand this way, and like it :D but could you explain more on how to make a backup and then deploy? my knowledge of MS SQL Server is bad, i started using it about a hour ago :\
    – Pomster
    Commented May 7, 2012 at 9:55
  • Is there a realsql server? will you use sql server express? is it enough with SQL Server Compact Edition? We can't get what you can use if you don't give extra information
    – JotaBe
    Commented May 7, 2012 at 10:03
  • 1
    I used MS SQl Server Management Studio 2008, MS SQL Management studio to Create a Database. I used a query to Create some columns. Now i wish to populate it with my C# app
    – Pomster
    Commented May 7, 2012 at 10:12
  • Will this app be deployed? Will you use it locally? Do you mind the kind of server that is needed?. I don't need to know how you did your database but where and why. I can't guess what you need!!!
    – JotaBe
    Commented May 7, 2012 at 10:20
  • 2
    Is this still valid for newer a SSMS? I can't find this in my SSMS v18.1. Commented Jan 15, 2020 at 15:06
182

Open SQL Server Management Studio and run following query. You will get connection string:

select
    'data source=' + @@servername +
    ';initial catalog=' + db_name() +
    case type_desc
        when 'WINDOWS_LOGIN' 
            then ';trusted_connection=true'
        else
            ';user id=' + suser_name() + ';password=<<YourPassword>>'
    end
    as ConnectionString
from sys.server_principals
where name = suser_name()
8
  • 7
    should be the accepted answer, because you get the connection, not only displayed
    – Tzwenni
    Commented Feb 1, 2022 at 14:28
  • 4
    This is flawless and nearly magical. Agree w. Tzwenni, this should be the accepted answer.
    – BoredBsee
    Commented Oct 7, 2022 at 3:33
  • 3
    Cool, we got the connection string and learn some built-in functions.
    – Arthas
    Commented Aug 8, 2023 at 8:43
  • 2
    This finally worked for me when I wanted to switch from SSMS to VS Code Extension. Commented Aug 24, 2023 at 8:52
  • 2
    Superb! One of those answers which gets the job done as well as teaches you something new! Commented Jan 25 at 14:40
151

A very simple way to retrieve a connection string, is to create a text file, change the extension from .txt to .udl.

Double-clicking the .udl file will open the Data Link Properties wizard.

Configure and test the connection to your database server.

Close the wizard and open the .udl file with the text editor of your choice and simply copy the connection string (without the Provider=<driver>part) to use it in your C# application.

sample udl file content

[oledb]
; Everything after this line is an OLE DB initstring
Provider=SQLNCLI11.1;Integrated Security=SSPI;Persist Security Info=False;User ID="";Initial Catalog=YOURDATABASENAME;Data Source=YOURSERVERNAME;Initial File Name="";Server SPN=""

what you need to copy from it

Integrated Security=SSPI;Initial Catalog=YOURDATABASENAME;Data Source=YOURSERVERNAME;

If you want to specify username and password you can adopt from other answers.

Tutorial: https://teusje.wordpress.com/2012/02/21/how-to-test-an-sql-server-connection/

6
  • If this doesn't work, there are some reg files that will make registry changes to enable/disable the UDL extension. I usually search the Windows folder for *.reg.
    – AMissico
    Commented Jan 16, 2015 at 2:30
  • Take a look at generate and save connection string in web config file youtu.be/1WgO7CDSmu8
    – anomepani
    Commented Nov 10, 2018 at 17:34
  • This was by far the easiest answer. Commented Oct 20, 2021 at 18:31
  • Does the credentials go from client to sql sqlserver as plain text? If so is there any way to secure it?
    – variable
    Commented Jan 14, 2022 at 14:55
  • @variable You can configure TLS for connections between clients and SQL Server.
    – Filburt
    Commented Jan 14, 2022 at 15:07
49

If you have installed and setup MS SQL Server and Management Studio, go to Visual Studio (Visual Studio not SQL Server Management Studio).

1] In Visual Studio go to Tools -> Connect to Database.

2] Under Server Name Select your Database Server Name (Let the list Populate if its taking time).

3] Under Connect to a Database, Select Select or enter a database name.

4] Select your Database from Dropdown.

5] After selecting Database try Test Connection.

6] If Test Connection Succeeds, Click Ok.

7] In Visual Studio go to View -> Server Explorer.

8] In Server Explorer window, Under Data Connections Select your Database. Right Click your Database -> Click Properties.

9] In Properties window you will see your Connection String.

28

On connectionstrings.com you can find the connection string for every DB provider. A connection string is built up with certain attributes/properties and their values. For SQL server 2008, it looks like this (standard, which is what you'll need here):

Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;

on myServerAddress, write the name of your installed instance (by default it's .\SQLEXPRESS for SQL Server Express edition). Initial catalog = your database name, you'll see it in SSMS on the left after connecting. The rest speaks for itself.

edit

You will need to omit username and password for windows authentication and add Integrated Security=SSPI.

1
  • Does the credentials go from client to sql sqlserver as plain text? If so is there any way to secure it?
    – variable
    Commented Jan 14, 2022 at 14:55
11

My solution was to use (2010).

In a new worksheet, select a cell, then:

Data -> From Other Sources -> From SQL Server 

put in the server name, select table, etc,

When you get to the "Import Data" dialog,
click on Properties in the "Connection Properties" dialog,
select the "Definition" tab.

And there Excel nicely displays the Connection String for copying
(or even Export Connection File...)

2
  • This works perfectly and doesn't require the connection to be setup in VS.
    – Robino
    Commented Jun 1, 2016 at 15:47
  • Haha, this is a super-creative yet effective way to get this. I tried it first simply because it didn't call for any prerequisite dependencies. Thank you.
    – Todd
    Commented Mar 23, 2020 at 18:17
11

If one uses the tool Linqpad, after one connects to a target database from the connections one can get a connection string to use.

  1. Right click on the database connection.
  2. Select Properties
  3. Select Advanced
  4. Select Copy Full Connection String to Clipboard

Result: Data Source=.\jabberwocky;Integrated Security=SSPI;Initial Catalog=Rasa;app=LINQPad

enter image description here


Remove the app=LinqPad depending on the drivers and other items such as Server instead of source, you may need to adjust the driver to suit the target operation; but it gives one a launching pad.

3
  • 2
    I approve of this post Commented Jun 6, 2018 at 10:43
  • The best solution
    – SamBerk
    Commented Dec 6, 2022 at 16:57
  • Linqpad FTW, again. Commented Apr 19 at 17:44
2

put below tag in web.config file in configuration node

 <connectionStrings>
<add name="NameOFConnectionString" connectionString="Data Source=Server;Initial Catalog=DatabaseName;User ID=User;Password=Pwd"
  providerName="System.Data.SqlClient" />

then you can use above connectionstring, e.g.

SqlConnection con = new SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["NameOFConnectionString"].ToString();
1
  • The question is how to obtain connection string to be able paste it in the code, not where to use it. Commented Feb 29 at 10:13
0

If you created Connection Manager in your project then you can simply pull the connection string from there.

String connection = this.dts.connections["<connection_manager_name>"];

And use this connection in:

using (var conn = new SqlConnection(connection))

Please correct me if I am wrong.

0

Easiest way my friends, is to open the server explorer tab on visual studio 2019 (in my case), and then try to create the connection to the database. After creating a succesful connection just right click on it and go to propierties. There you will find a string connection field with the correct syntax!...This worked for me because I knew my server's name before hand....just couldn't figure out the correct syntax to run my ef scaffold...

-3

The sql server database will be stored by default in the following path

<drive>:\Program Files\Microsoft SQL Server\MSSQL.X\MSSQL\Data\

, where <drive> is the installation drive and X is the instance number (MSSQL.1 for the first instance of the Database Engine). Inorder to provide the connection string you should know what is the server name of the sql server database, where you have stored followed by instance of the database server.

Generally the server name will be like the ip address of the machine where the database is attached and the default instance will be SqlExpress

A connection string contains Data Source name i.e., server name, Initial catalog i.e., database name, user id i.e., login user id of the database, password i.e., login password of the database.

3
  • 2
    How do i obtain the connection string?
    – Pomster
    Commented May 7, 2012 at 9:41
  • 1
    I took a look in Program files\Microsoft SQl Server and i have no idea what i'm looking for?
    – Pomster
    Commented May 7, 2012 at 9:43
  • you no need to look for the database storage folder, see the link i have given for connection string and write your connection string. Commented May 7, 2012 at 9:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.