Luke Makk
Luke Makk

Reputation: 1197

Finding data source for sql server connection in C#

trying to connect to sql server from c#, using the format

    private void ConnectToSQL() 
    {    
        string connectionString = @"Data Source= ____;Initial Catalog=____;User ID=_____;Password=_____";    
        using (SqlConnection objSqlConnection = new SqlConnection (connectionString))    
        {        
           try {            
               objSqlConnection.Open();            
               objSqlConnection.Close();            
               Response.Write("Connection is successfull");        
           } 
           catch (Exception ex) 
           {           
               Response.Write("Error : " + ex.Message.ToString());        
           }    
        }
     }

how do I find what the data source and initial catalogue are from management studio. Having trouble establishing a connection.

Upvotes: 1

Views: 18835

Answers (4)

Paul Chernoch
Paul Chernoch

Reputation: 5553

See http://social.msdn.microsoft.com/Forums/vstudio/en-US/a7e276c4-7d7d-4f37-bbbe-4a97e500b9b2/connection-string-in-c

It shows how to use SqlConnectionStringBuilder. Then if you get the parts right, it will make a well-constructed connection string for you when you call builder.ConnectionString.

One tripping point is if you are not using the default instance. If you use a named SQL Server instance, you need servername\instancename to identify the instance.

Upvotes: 3

Keith Payne
Keith Payne

Reputation: 3082

You cannot get it from SSMS.

You can get it from Visual Studio, however. From the main menu,

View -> Server Explorer.

Expand Data Connections.

Add a connection to your server.

After adding the connection, right-click on the connection -> Properties.

There is a Connection String property that you can copy-and-paste.

Upvotes: 3

Ahmed Alaa El-Din
Ahmed Alaa El-Din

Reputation: 1833

if you use this in localhost you can use this

<configuration>
  <connectionStrings>
    <add name="ConnStringDb1" connectionString="Data Source=localhost;Initial Catalog=db_name;Integrated Security=True;" providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

and your code

using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnStringDb1"].ToString()))
{}

Upvotes: 0

Justin
Justin

Reputation: 3397

Data source is the name of the MS SQL server instance you are connecting to and Inital Catalog is the database name you want to connect to.

EG: You have a default instance of MS SQL server Express and a database named Northwind.

The datasource would be .\SQLEXPRESS (the "." stands for the local machine) and the inital catalog would be Northwind


A very useful resource Connectionstrings.com

Upvotes: 4

Related Questions