【问题标题】:Not able to get Datatable return type in to object无法获取数据表返回类型到对象
【发布时间】:2013-02-28 11:19:07
【问题描述】:

我已经创建了从数据库获取数据的方法。此方法将 DataTable 作为返回类型。尝试调用此方法时,它向我抛出了对象引用的异常,未设置对象的实例。这是方法以及我如何使用它。

 public DataTable executeSelect (String _query, SqlParameter[] sqlParameter)
    {
        SqlCommand myCommand = new SqlCommand();
        DataTable dataTable = new DataTable();
        dataTable = null;
        DataSet ds = new DataSet();
        try
        {
            myCommand.Connection = openConnection();
            myCommand.CommandText = _query;
            myCommand.Parameters.AddRange(sqlParameter);
            myCommand.ExecuteNonQuery();
            myadapter.SelectCommand = myCommand;
            myadapter.Fill(ds);
            dataTable = ds.Tables[0];
        }
        catch (SqlException e)
        {
            Console.Write( e.StackTrace.ToString());

            return null;
        }
        finally
        {

        }
        return dataTable;
    }

下面的代码显示了如何使用上述方法生成数据表

            string sp_name = "sLot";
            SqlParameter[] param = new SqlParameter[]{
                 new SqlParameter("@stype","ML"),
                new SqlParameter("@ttype","B"),
                new SqlParameter("@code",comp_code)

            };               

            DataTable data = dbc.executeSelect(sp_name, param); 

注意:这里使用存储过程名称“sLot”

【问题讨论】:

  • 最后一行抛出错误,即 DataTable data = dbc.executeSelect(sp_name, param);

标签: c# database winforms datatable


【解决方案1】:

我假设你得到一个例外,因此你返回 null 而不是 DataTable。如果你使用一个,你必须将CommandType 设置为StoredProcedure

myCommand.CommandType = CommandType.StoredProcedure;

NullReferenceException 当然还有其他可能的原因,但您没有提供足够的信息。如果最后一行抛出异常,注释为dbc 为空。您可以将executeSelect 设为静态或创建声明该方法的类型的实例。

【讨论】:

  • 它在进入executeSelect方法之前抛出错误,即这里DataTable data = dbc.executeSelect(sp_name, param);
  • 你说得对,我忘了用 new 关键字声明 dbc,因为我印象中它是一个静态方法。谢谢蒂姆。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-17
  • 1970-01-01
  • 1970-01-01
  • 2012-03-15
  • 1970-01-01
  • 2012-05-04
相关资源
最近更新 更多