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

C#三层架构WinForm CRUD开发中sda.Fill(dt)抛出未处理异常求助

问题根源分析

你遇到的ADP_ConnectionRequired_Fill异常,核心原因有两个:

  • 创建的SqlCommand未关联到已实例化的SqlConnection对象,导致SqlDataAdapter填充数据时找不到数据库连接。
  • 错误将CommandType设置为CommandType.StoredProcedure,但传入的是直接SQL查询语句(Select * from emptable),而非存储过程名称。

修正后的代码

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace _3_tierProject1
{
    class DLL
    {
        string constring = ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString();

        public DataTable selectDAL()
        {
            DataTable dt = new DataTable();
            using (SqlConnection conn = new SqlConnection(constring))
            {
                // 创建SqlCommand时直接关联Connection
                using (SqlCommand cmd = new SqlCommand("Select * from emptable", conn))
                {
                    // 执行普通SQL语句,显式指定CommandType为Text(默认值,可省略但可读性更强)
                    cmd.CommandType = CommandType.Text;
                    using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                    {
                        sda.Fill(dt);
                    }
                }
            }
            return dt;
        }
    }
}

关键修正点说明

  • 关联SqlCommand与SqlConnection:创建SqlCommand时将第二个参数指定为已实例化的conn,或通过cmd.Connection = conn手动关联,确保SqlDataAdapter能获取到有效连接。
  • 修正CommandType:执行普通SQL语句时使用CommandType.Text;若要调用存储过程,再设置为CommandType.StoredProcedure并传入存储过程名称。
  • 连接自动管理:SqlDataAdapter的Fill方法会自动打开未激活的连接,执行完成后自动关闭,无需手动调用conn.Open()和conn.Close()。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 16:42:46