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

丶灬走出姿态 提交于 2021-02-11 17:43:15

问题


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.


回答1:


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




回答2:


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



回答3:


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



回答4:


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;



回答5:


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>


来源:https://stackoverflow.com/questions/5581425/how-to-connect-to-the-remote-database-using-connection-string-in-c-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!