簡體   English   中英

如何使用C#.net中的連接字符串連接到遠程數據庫

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

每一個。 我想使用C#.net中的Sql Connection String連接遠程數據庫,我正在嘗試執行該操作,但是連接失敗。 我是C#.net與數據庫連接的新手。 誰能告訴我如何編寫連接字符串。

檢查此網站以獲取特定格式: http : //www.connectionstrings.com/

以下是一些代碼,這些代碼將連接到名為myServer的服務器上名為myDatabase的數據庫 ,在myTable表中查詢列myColumn ,並將返回的數據插入字符串列表中。

雖然這段代碼絕非精妙或完美,但確實顯示了在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());
    }
  }
}

在這方面沒有區別 用於連接到遠程服務器數據庫的連接字符串的寫法與您用於連接到本地數據庫服務器的寫法相同。

但是,只有Data Source更改。

下面是一個示例連接字符串

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

但是默認情況下,sql server未配置為Sql Server Authentication ,因此您需要啟用

您也可以在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>

以下是幾個示例:

具有集成安全性

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

使用用戶名和密碼

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM