简体   繁体   English

如何使用C#.net中的连接字符串连接到远程数据库

[英]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. 我想使用C#.net中的Sql Connection String连接远程数据库,我正在尝试执行该操作,但是连接失败。 I am new to C#.net connections to the Database. 我是C#.net与数据库连接的新手。 Can any one pls tell me how to write the Connection String. 谁能告诉我如何编写连接字符串。

检查此网站以获取特定格式: 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. 以下是一些代码,这些代码将连接到名为myServer的服务器上名为myDatabase的数据库 ,在myTable表中查询列myColumn ,并将返回的数据插入字符串列表中。

While by no means exaustive or perfect, this snippet does show some of the core aspects of working with data in C#. 虽然这段代码绝非精妙或完美,但确实显示了在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. 但是,只有Data Source更改。

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未配置为Sql Server Authentication ,因此您需要启用

You can also do that in web.config file 您也可以在web.config文件中执行此操作

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

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM