You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于.NET Framework的C++程序连接SQL Server失败求助

问题描述

我使用C++在.NET Framework环境下开发应用程序,尝试连接SQL Server时失败,错误信息如下:

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 that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

应用程序代码如下:

#pragma endregion
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
    try
    {
        String^ connectionstring = "Data Source=localhost\sqlexpress;Initial Catalog=root_info;Integrated Security=True;";
        SqlConnection con(connectionstring);
        con.Open();
        String^ sqlquery = "insert into root_table values('"+this->textBox1+"','"+this->textBox2 +"')";
        SqlCommand cmd(sqlquery, % con);
        cmd.ExecuteNonQuery();
        con.Close();
        MessageBox::Show("datasubmited successfully", "success", MessageBoxButtons::OK);
    }
    catch (Exception^ ex)
    {
        throw ex;
    }
}
};
}
排查与修复方案

1. 连接字符串错误修复

  • 转义反斜杠:C++/CLI字符串中,反斜杠\是转义字符,需要写成\\才能被正确解析。你的连接字符串里localhost\sqlexpress会被错误解析,修正后:
    String^ connectionstring = "Data Source=localhost\\sqlexpress;Initial Catalog=root_info;Integrated Security=True;";
    
  • 确认实例名称:检查SQL Server Express的实例名是否为SQLEXPRESS——打开SQL Server配置管理器,查看SQL Server服务的名称。如果是默认实例,连接字符串改为Data Source=localhost;或Data Source=.;。

2. SQL Server服务与配置检查

  • 启动SQL Server服务:打开services.msc,找到SQL Server (SQLEXPRESS)服务,确保其状态为“正在运行”,未启动则手动启动。
  • 允许远程连接:打开SQL Server Management Studio,右键目标实例→属性→连接,勾选“允许远程连接到此服务器”。
  • 启用Named Pipes协议:打开SQL Server配置管理器→SQL Server网络配置→SQLEXPRESS的协议,启用Named Pipes,之后重启SQL Server服务。

3. 代码安全性与可靠性优化

  • 避免SQL注入:直接拼接文本框内容会导致严重的SQL注入风险,改用参数化查询:
    String^ sqlquery = "insert into root_table values(@val1, @val2)";
    SqlCommand cmd(sqlquery, % con);
    cmd->Parameters->AddWithValue("@val1", this->textBox1->Text);
    cmd->Parameters->AddWithValue("@val2", this->textBox2->Text);
    
  • 自动管理资源:用using语句自动释放SqlConnection和SqlCommand资源,避免手动关闭连接时的异常:
    try
    {
        String^ connectionstring = "Data Source=localhost\\sqlexpress;Initial Catalog=root_info;Integrated Security=True;";
        using (SqlConnection con(connectionstring))
        {
            con->Open();
            String^ sqlquery = "insert into root_table values(@val1, @val2)";
            using (SqlCommand cmd(sqlquery, % con))
            {
                cmd->Parameters->AddWithValue("@val1", this->textBox1->Text);
                cmd->Parameters->AddWithValue("@val2", this->textBox2->Text);
                cmd->ExecuteNonQuery();
                MessageBox::Show("数据提交成功", "成功", MessageBoxButtons::OK);
            }
        }
    }
    catch (Exception^ ex)
    {
        MessageBox::Show("错误:" + ex->Message, "失败", MessageBoxButtons::OK);
    }
    
  • 异常处理优化:不要在catch块中直接throw ex,这会重置异常调用栈信息,建议直接throw或捕获后向用户展示错误信息。

内容的提问来源于stack exchange,提问作者Polas Hacks

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 10:55:14