简体   繁体   中英

error 26- error locating server/instance specified

I designed a C# desktop app in visual studio 2019 and for database used sql server express 2019 edition. i am trying to run this app on another pc. i have installed sql server express 2019 in the other pc also MS server management studio 2019 installed and restored the database. everything works fine like login,saving updating,deleting but when i try to fetch data to datagridview it shows "system.data.sqlclient.sqlexception - a network related or instance specific error occurred while establishing a connection to sql server. the server was not found or was not accessible. verify instance name is correct and sql server is configured to allow remote connections.(provider: sql network interfaces, error: 26 - error locating server/instance specified)."

all the ports are enabled and firewall rule is also enabled in the client pc.

i am using the below connection string for the connection.

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

Please help anyone as i am not able to get what is the problem going on.

Belowcode is working

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

but this is not working.it shows the error when i try to fetch the data.

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

数据网格的数据集 应用程序的所有文件

Throw your Connection class away, and pass the connection string to the DataAdapter. Don't bother opening or closing the connection; DataAdapter knows how to open a connection if it's closed

Put the connectionstring into the Settings

在此处输入图像描述

Use parameters

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

   }
}

Use parameters

Just in case you missed it: USE PARAMETERS . Never again, in your life ever, should you concatenate a value into an SQL string. Ever. There is no reason to do it, and doing it will result in the software you create being hacked / you getting fired / both

Also, don't store passwords in plain text, ever. Salt and hash them. I've used string.GetHashcode() for demo purposes, which is not good but better than plaintext


Do the same thing to the not working code:

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

this issue also confusing me a few days after the IT guy do some security settings to the SQL Server. i have an EntityFramework for the Web application and a desktop application. after i did some setting on the SQL Server, the Web application comeback to work, but the desktop still with issue. but i used the some connection string for the both application, it make no sense one is work but the other doesn't. then i searched a lot until i found some one said need add a port number 1433 after the $ServerName$DatabaseInstanceName,1433 at here http://www.windows-tech.info/15/9f6dedc097727100.php . after i added it. the exception became: System.Data.SqlClient.SqlException: Login failed for user 'domain\name-PC$'. then i found this link System.Data.SqlClient.SqlException: Login failed for user : System.Data.SqlClient.SqlException: Login failed for user it said need add Trusted_Connection=False;. the whole connection string should be like: data source=XXXXX\SQLSERVER,1433;initial catalog=XXXDB;user id=UserID;password=PWD;Trusted_Connection=False;MultipleActiveResultSets=True;

hope this answer will help the ones out off Generic exception: "Error: 26-Error Locating Server/Instance Specified)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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