对于ExecuteReader: Connection 属性尚未初始化问题的解决

本文探讨了SqlCommand中未正确设置SqlConnection属性导致的问题,并提供了解决方案。在使用SqlCommand对象时,若未在构造函数中指定SqlConnection实例,则可能引发运行时错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题出在SqlCommand中没有定义SqlConnection属性,

即代码为:SqlCommand cmd= new SqlCommand();

以上问题出在没有将属性加入new SqlCommand后的()中

namespace _2 { public class Dao2 : IDisposable { private SqlConnection _connection; // 添加公共属性暴露连接对象 public SqlConnection Connection => _connection; public void Connect() { // 实际项目中应从配置读取连接字符串 _connection = new SqlConnection("Server=LAPTOP-265KA3NF;Database=pointnote;Integrated Security=True;"); _connection.Open(); } public int ExecuteParameterized(string sql, List<SqlParameter> parameters) { using (SqlCommand cmd = new SqlCommand(sql, _connection)) { // 添加所有参数 cmd.Parameters.AddRange(parameters.ToArray()); // 执行并返回受影响行数 return cmd.ExecuteNonQuery(); } } // 增加一个方法用于执行查询并返回SqlDataReader public SqlDataReader Read(string sql) { SqlCommand cmd = new SqlCommand(sql, _connection); return cmd.ExecuteReader(); } // 关闭连接的方法(可选) public void Disconnect() { if (_connection != null && _connection.State != ConnectionState.Closed) { _connection.Close(); } } // 添加 Close 方法 public void Close() { if (_connection != null && _connection.State != ConnectionState.Closed) { _connection.Close(); _connection = null; } } // 实现 IDisposable 模式 public void Dispose() { Close(); GC.SuppressFinalize(this); } internal int Execute(string sql) { int rowsAffected = 0; try { using (SqlCommand cmd = new SqlCommand(sql, _connection)) { rowsAffected = cmd.ExecuteNonQuery(); } } catch (SqlException ex) { // 记录日志或进行其他异常处理操作 Console.WriteLine($"执行SQL语句时发生错误:{ex.Message}"); } return rowsAffected; } } }怎么实现_connection初始化
最新发布
07-04
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值