You need to enable JavaScript to run this app. 部署至其他PC的C#桌面应用连SQL Server Express 2019取数报Error 26
优惠活动
大模型
产品
解决方案
定价
更多

部署至其他PC的C#桌面应用连SQL Server Express 2019取数报Error 26

排查:C#桌面应用部署后DataGridView加载数据报SQL连接错误

基础环境与故障现象

  • 开发侧:基于Visual Studio 2019开发的C# WinForm桌面应用,配套数据库为SQL Server Express 2019
  • 目标部署侧:已完成SQL Server Express 2019、SQL Server Management Studio 2019安装,还原目标数据库,已开放SQL对应端口、配置防火墙放行规则
  • 功能异常点:登录、数据增删改功能运行正常,仅在将数据加载到DataGridView时抛出异常:

System.Data.SqlClient.SqlException:建立与SQL Server连接时出现网络相关或实例特定错误,未找到或无法访问服务器(提供程序:SQL Network Interfaces,错误: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;
    }
}

核心问题定位与修复方向

  • 设计时数据源硬编码(最高概率诱因):通过VS拖放控件为DataGridView配置数据源时,IDE会自动生成强类型DataSet/TableAdapter组件,该组件会将开发环境下的SQL实例连接字符串硬编码写入应用配置文件。窗体加载时,设计器绑定的数据源初始化逻辑会优先触发,直接使用硬编码的开发环境连接字符串发起请求,而非自定义Connection类中的连接配置,自然会因为找不到开发机的SQL实例抛出错误26。
    • 修复方式:移除DataGridView的设计时自动绑定数据源,完全通过手写代码实现数据加载;检查项目配置文件中的connectionStrings节点,删除所有硬编码的开发环境连接字符串,替换为目标环境的有效连接配置。
  • 共享SqlConnection实例状态异常:自定义Connection类将SqlConnection作为类级别的常驻成员,未采用“用时打开、用完释放”的标准模式,在跨窗体切换、连接被数据库端空闲回收后,可能出现连接状态判断失效的问题。
    • 修复方式:重构连接逻辑,每次执行数据库操作时实例化新的SqlConnection,使用using块自动释放连接资源,避免连接长期驻留带来的状态异常。
  • 数据读取未及时释放资源:当前学生数据加载逻辑中,SqlDataReader使用后未显式关闭,长期运行可能造成连接池耗尽,间接引发连接错误。

内容的提问来源于stack exchange,提问作者Bhaskar Roy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.04 21:06:03