How to connect to the Remote Database using Connection String in C#.net

every one. I want to connect a remote database using Sql Connection String in C#.net, I am trying it to do, but failed to connect. I am new to C#.net connections to the Database. Can any one pls tell me how to write the Connection String.

Upvotes: 0

Views: 31277

Answers (5)

Pramesh
Pramesh

Reputation: 1244

You can also do that in web.config file

<configuration>
<ConnectionStrings>
<add name="YourConnectionString" connectionString="Data Source=Nameofserver;
InitialCatalog=NameofDatabase;Persist Security Info=True;
UserID=DatabaseUserID;Password=DatabasePassword" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>

Upvotes: 0

Waqas Raja
Waqas Raja

Reputation: 10872

There is no difference in this regard. The connection string to connect to remote server database is written same as you write to connect to local database server.

However, only Data Source changes.

Below is a sample connection string

User ID=dbUserName;Password=dbUserPwd;Initial Catalog=dbName;Data Source=remoteMachine\serverInstanceNameIfAny;

But by default sql server is not configured to Sql Server Authentication, so you need to enable

Upvotes: 1

SWeko
SWeko

Reputation: 30892

Here is a little bit of code that will connect to a dabase called myDatabase on a server called myServer, query the myTable table for the column myColumn, and insert the returned data into a list of strings.

While by no means exaustive or perfect, this snippet does show some of the core aspects of working with data in C#.

List<string> results = new List<string>();
SqlConnection conn = new SqlConnection("Data Source = myServerAddress; Initial Catalog = myDataBase; User Id = myUsername; Password = myPassword;");
using (SqlCommand command = new SqlCommand())
{
  command.Connection = conn;
  command.CommandType = CommandType.Text;
  command.CommandText = "Select myColumn from myTable";
  using (SqlDataReader dr = command.ExecuteReader())
  {
    while (dr.Read())
    {
      results.Add(dr["myColumn"].ToString());
    }
  }
}

Upvotes: 1

WraithNath
WraithNath

Reputation: 18013

Here are a couple of examples:

With Integrated Security

Server=RemoteMachineName\Intance; Initial Catalog=DatabaseName; Integrated Security=true;

With username and password

Server=RemoteMachineName\Intance; Initial Catalog=DatabaseName; UID=Username; PWD=Password;

Upvotes: 0

BrandonZeider
BrandonZeider

Reputation: 8152

Check this website for the specific format: http://www.connectionstrings.com/

Upvotes: 8

Related Questions