开发者

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

开发者 https://www.devze.com 2023-02-22 14:27 出处:网络
every one. I want to connect a remote database using Sql Connection String in C#.net, I am trying it to do, but fail开发者_运维问答ed to connect. I am new to C#.net connections to the Database. Can an

every one. I want to connect a remote database using Sql Connection String in C#.net, I am trying it to do, but fail开发者_运维问答ed to connect. I am new to C#.net connections to the Database. Can any one pls tell me how to write the Connection String.


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


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());
    }
  }
}


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

  • Sql server authentication
  • Also Create a Log in user in the database


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;


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消