【问题标题】:data adapter.select command.connection数据适配器。选择命令。连接
【发布时间】:2015-09-30 04:20:27
【问题描述】:

我正在使用下面的代码从数据库中获取数据。但是,当断点进入 var k 之后的任何行时,会立即引发异常。

 DataSet ds = new DataSet();
            try
            {
                using (SqlConnection con = new SqlConnection())

                {
                    con.ConnectionString = @"Data Source = sql\db1,5000; Initial Catalog = uatdb; Integrated Security = SSPI";

                    using (SqlDataAdapter da = new SqlDataAdapter())
                    {
                        var k = con.State;

更新:
从答案中添加了这一行,但没有帮助,仍然是同样的错误

                        da.selectcommand=new sqlcommand();

                        da.SelectCommand.Connection.ConnectionString= con.ConnectionString;
                        da.SelectCommand.CommandText = "usp_checkstatus";
                        da.SelectCommand.Parameters.Add("@id", SqlDbType.Int).Value = TextBox1.Text.ToString(); ;
                        da.SelectCommand.CommandType = CommandType.StoredProcedure;


                        //  da.SelectCommand.Parameters.AddWithValue("@buildid", TextBox1.Text);

                        da.Fill(ds);
                        return ds;


                    }
                }
            }

****异常详情:****

对象引用未设置为对象实例。连接状态始终关闭,DB,连接字符串正确,我没有打开连接,因为数据适配器将为我打开连接。

答案可能很简单,但它现在占用了我近 4 个小时的时间。非常感谢任何帮助。

注意: 我可以使用 sqlcommand 来处理下面问题中的代码,但我想尝试使用数据适配器

How to use a DataAdapter with stored procedure and parameter

【问题讨论】:

  • 这真的是你的代码吗?因为没有正确的大小写就无法编译
  • 它的编译,我只删除了 catch 块。我从 VS 复制粘贴

标签: c# sqldataadapter


【解决方案1】:

您应该将创建的 SqlConnection 设置为您的 SqlDataAdapter。没有必要打开它,因为如果它关闭,适配器会为您打开它,但适配器必须知道连接。

DataSet ds = new DataSet();
try
{
    using (SqlConnection con = new SqlConnection(@"Data Source = sql\db1,5000; 
           Initial Catalog = uatdb; Integrated Security = SSPI"))
    using (SqlDataAdapter da = new SqlDataAdapter("usp_checkstatus", con))
    {
        da.SelectCommand.CommandType = CommandType.StoredProcedure;
        da.SelectCommand.Parameters.Add("@id", SqlDbType.Int).Value = Convert.ToInt32(TextBox1.Text);
        da.Fill(ds);
        return ds;
    }
}

也不需要创建特定的SqlCommand。当您创建 Adapter 并传递存储过程名称时,会自动为您创建一个新的 SqlCommand,当然您仍然需要设置它的参数和它的 CommandType。 (关于参数的注释,我不确定这是否会导致你的 sp 出现错误的结果,但如果你想传递一个整数然后将输入转换为整数似乎是安全的)

【讨论】:

  • 感谢整数转换的额外提示,
【解决方案2】:

您必须实例化SelectCommand 属性:

 using (SqlDataAdapter da = new SqlDataAdapter())
   {
    da.SelectCommand = new SqlCommand();
    da.SelectCommand.Connection=con;
    ..
   }

或创建SqlCommand 对象并将其引用分配给SelectCommand 属性。

var cmd = new SqlCommand();
cmd.CommandText = "your-proc-name";
cmd.Connection = con;
.....
adp.SelectCommand = cmd;

【讨论】:

  • 首先非常感谢您的即时回复,但仍然是同样的问题。用您建议的代码更新了我的问题
  • @TheGameiswar 设置con 引用Connection 属性
猜你喜欢
  • 2011-09-27
  • 2011-01-04
  • 1970-01-01
  • 2016-11-25
  • 2017-03-12
  • 2016-10-16
  • 2013-03-02
  • 1970-01-01
  • 2017-04-07
相关资源
最近更新 更多