簡體   English   中英

錯誤:無法打開與 SQL Server 的連接

[英]Error: Could not open a connection to SQL Server

我是 Asp.Net 的新手,現在我正面臨這個問題。 我已經嘗試了很多方法,我從谷歌和這里得到。 但我仍然找不到解決方案。 我已嘗試將數據源更改為 127.0.0.1,但仍然出現相同的錯誤。 當我使用MySql.Data.MySqlClient時,它實際上可以連接到數據庫。 但是當我使用System.Data.SqlClient時失敗了你們能幫我嗎? 非常感謝。

背后的代碼:

private DataTable GetData(string query)
        {
            DataTable dt = new DataTable();
            string constr = ConfigurationManager.ConnectionStrings["WebAppConnStringSql"].ConnectionString;
            using (SqlConnection cons = new SqlConnection(constr))
            {           
                using (SqlCommand cmds = new SqlCommand(query))
                {
                    using (SqlDataAdapter sda = new SqlDataAdapter())
                    {
                        cmds.CommandType = CommandType.Text;
                        cmds.Connection = cons;
                        sda.SelectCommand = cmds;
                        **sda.Fill(dt);** //Error occurs here
                    }
                }
                return dt;
            }

網頁配置

<connectionStrings>
    <add name="WebAppConnStringSql"
         connectionString="Data Source=localhost;Initial Catalog=vbsite;Integrated Security=True"
         providerName="System.Data.SqlClient"/>
  </connectionStrings>

錯誤:*類型為“System.Data.SqlClient.SqlException”的異常發生在 System.Data.dll 中,但未在用戶代碼中處理

附加信息:建立與 SQL Server 的連接時發生與網絡相關或特定於實例的錯誤。 服務器未找到或無法訪問。 驗證實例名稱是否正確以及 SQL Server 是否配置為允許遠程連接。 (提供程序:命名管道提供程序,錯誤:40 - 無法打開與 SQL Server 的連接)*用戶代碼未處理 SqlException

您應該打開連接SqlConnection.Open()

using (SqlConnection cons = new SqlConnection(constr))
{           
   cons.Open();
   using (SqlCommand cmds = new SqlCommand(query))
   {                   
      using (SqlDataAdapter sda = new SqlDataAdapter())
      {
         cmds.CommandType = CommandType.Text;
         cmds.Connection = cons;
         sda.SelectCommand = cmds;
         **sda.Fill(dt);** //Error occurs here
      }
   }
   return dt;
}

暫無
暫無

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

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