【问题标题】:error 26- error locating server/instance specified错误 26 - 定位服务器/指定实例时出错
【发布时间】:2021-02-08 10:44:08
【问题描述】:

我在 Visual Studio 2019 中设计了一个 C# 桌面应用程序,并为数据库使用了 sql server express 2019 版。我正在尝试在另一台电脑上运行这个应用程序。我已经在另一台电脑上安装了 sql server express 2019,还安装了 MS server management studio 2019 并恢复了数据库。一切正常,例如登录,保存更新,删除,但是当我尝试将数据提取到 datagridview 时,它显示“system.data.sqlclient.sqlexception - 与 sql server 建立连接时发生网络相关或实例特定错误。服务器不是找到或无法访问。验证实例名称是否正确,并且 sql server 配置为允许远程连接。(提供者:sql 网络接口,错误:26 - 错误定位服务器/指定实例。"

所有端口均已启用,并且客户端电脑中的防火墙规则也已启用。

我正在使用下面的连接字符串进行连接。

class Connection
  {
       SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=icon;Integrated Security=True");

    public SqlConnection active()
    {
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        return con;
    }
}

请帮助任何人,因为我无法解决问题所在。

下面的代码正在运行

 private void loginBtn_Click(object sender, EventArgs e)
     {
        Connection con = new Connection();
        SqlCommand cmd = new SqlCommand("select * from [user] where 
        Username='" + usernameTxt.Text + "'and password='" + passwordTxt.Text 
        + "'", con.active());
        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        sda.Fill(dt);
        if (dt.Rows.Count > 0)
        {
            MessageBox.Show("Login Successful", "Sucsess", 
              MessageBoxButtons.OK, MessageBoxIcon.Information);
            new dashboard().Show();
            this.Hide();
        }

但这不起作用。当我尝试获取数据时它显示错误。

public partial class AllSudent : Form
{
    public AllSudent()
    {
        InitializeComponent();
    }

    Connection con = new Connection();
    public int studentID;
    private void AllSudent_Load(object sender, EventArgs e)
    {
       
        GetStudentsRecord();
    }

    public void GetStudentsRecord()
    {
        SqlCommand cmd = new SqlCommand("Select * From [student]", 
        con.active());
        DataTable dt = new DataTable();
        SqlDataReader sdr = cmd.ExecuteReader();
        dt.Load(sdr);

        sdataGridView.DataSource = dt;
    }

【问题讨论】:

  • 所以你的说法是该方法用于获取例如登录时建立连接,从用户表中选择数据可以正常工作,但是当用于获取某些网格的数据时,使用完全相同的方法,它会失败吗?发布工作和失败的代码
  • 顺便说一句,您在这里使用的模式看起来不太好 - 事物的结构方式可能导致连接打开的时间超过必要的时间、耗尽池或拥有一个类关闭另一个类仍在使用的连接。您应该在using 中按需创建新连接并确保它们在完成后关闭,否则您将破坏框架中内置的所有连接管理(池),即期望以特定方式使用连接
  • 嗨@CaiusJard ..我已经编辑了我面临问题的问题..还上传了数据集和所有文件图片..还建议我应该如何编写连接字符串,因为我是新手并为我的班级做一个项目。
  • "SqlCommand cmd = new SqlCommand("select * from [user] where Username='" + usernameTxt.Text + "'and password='" + passwordTxt.Text" 这是非常危险的(是的,因为我真的在大喊大叫!)。这里有多个问题;您将密码存储为纯文本(大量问题),并且很容易注入。修复你的设计,永远不要像 parametrise 那样将值注入你的 SQL,并停止存储纯文本密码;盐和哈希它们。有人可以通过输入他们的用户名' OR 1=1;-- 和密码轻松进入您的系统。

标签: c# sql-server


【解决方案1】:

扔掉你的 Connection 类,并将连接字符串传递给 DataAdapter。不要费心打开或关闭连接; DataAdapter 知道在连接关闭时如何打开连接

将连接字符串放入设置中

使用参数

 private void loginBtn_Click(object sender, EventArgs e)
 {
    using(var sda = new SqlDataAdapter("select * from [user] where Username=@user and password=@pass", Properties.Settings.Default.ConStr)
    {
      //USE PARAMETERS
      sda.SelectCommand.Parameters.Add("@user", SqlDbType.VarChar, usernameTxt.Text.Length).Value = usernameTxt.Text;
      sda.SelectCommand.Parameters.Add("@pass", SqlDbType.VarChar, passwordTxt.Text.Length).Value = passwordTxt.Text.GetHashcode(); //DO NOT store your passwords in plain text!!

      var dt = new DataTable();
      sda.Fill(dt);
      if (dt.Rows.Count > 0)
      {
        MessageBox.Show("Login Successful", "Sucsess", 
          MessageBoxButtons.OK, MessageBoxIcon.Information);
        new dashboard().Show();
        this.Hide();
      }

   }
}

使用参数

以防万一您错过了:使用参数。在您的生活中,再也不会将值连接到 SQL 字符串中。曾经。没有理由这样做,这样做will result in the software you create being hacked/你被解雇了/两者兼而有之

另外,永远不要以纯文本形式存储密码。盐和哈希它们。我使用string.GetHashcode() 进行演示,这不好但比纯文本好


对不工作的代码做同样的事情:

public void GetStudentsRecord()
{
    using(var sda = new SqlDataAdapter("Select * From [student]", Properties.Settings.Default.ConStr)){
      var dt = new DataTable();
      sda.Fill(dt);

      sdataGridView.DataSource = dt; 
    }
}

【讨论】:

  • 非常感谢@Caius jard。它解决了这个问题。 :-)
【解决方案2】:

在 IT 人员对 SQL Server 进行一些安全设置后几天,这个问题也让我感到困惑。我有一个用于 Web 应用程序和一个桌面应用程序的 EntityFramework。在我对 SQL Server 进行一些设置后,Web 应用程序恢复工作,但桌面仍然存在问题。但我对这两个应用程序都使用了一些连接字符串,一个是工作但另一个没有意义是没有意义的。然后我搜索了很多,直到我发现有人说需要在 $ServerName$DatabaseInstanceName,1433 之后添加一个端口号 1433 在这里 http://www.windows-tech.info/15/9f6dedc097727100.php 。在我添加之后。异常变为:System.Data.SqlClient.SqlException:用户“域\名称-PC$”登录失败。然后我找到了这个链接System.Data.SqlClient.SqlException: Login failed for user: System.Data.SqlClient.SqlException: Login failed for user it said need add Trusted_Connection=False;.整个连接字符串应该是这样的:data source=XXXXX\SQLSERVER,1433;initial catalog=XXXDB;user id=UserID;password=PWD;Trusted_Connection=False;MultipleActiveResultSets=True;

希望这个答案能帮助解决通用异常:“错误:26-错误定位服务器/指定实例)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-07
    • 2018-01-05
    • 1970-01-01
    • 2016-02-26
    • 1970-01-01
    相关资源
    最近更新 更多