【问题标题】:sqlcommand c# method with sql paramather带有sql参数的sqlcommand c#方法
【发布时间】:2019-07-30 11:59:22
【问题描述】:

我有这个方法,我在基类中有这个方法,它可以帮助我从子类中选择任何东西,也可以减少代码重复。问题是当我调用它时,我收到一个错误,即 NullReferenceException(当我查找它时,我发现方法中的命令为空)。 这是有问题的方法: 这种方式我已经知道如何使用,但另一种我不知道

SqlCommand command = new SqlCommand("select * from Customers where idCustomer=@idCustomer", OpenConnection());
command.Parameters.AddWithValue("@idCustomer", Id);
SqlDataReader reader = command.ExecuteReader();
Customer Onecustomer = null;
if (reader.Read())
{
    Onecustomer = ReadCustomer(reader);
}

protected DataTable ExecuteSelectQuery(String query, params SqlParameter[] sqlParameters)
{
    SqlCommand command = new SqlCommand();
    DataTable dataTable;
    DataSet dataSet = new DataSet();

    try
    {
        command.Connection = OpenConnection();
        command.CommandText = query;
        command.Parameters.AddRange(sqlParameters);
        command.ExecuteNonQuery();
        adapter.SelectCommand = command;
        adapter.Fill(dataSet);
        dataTable = dataSet.Tables[0];
    }
    catch (SqlException e)
    {
        return null;
        throw new Exception("Error :" + e.Message);
    }
    finally
    {
        CloseConnection();
    }
    return dataTable;
}

我怎么称呼它

string author = "Alfred Schmidt";
int id = 1;

//  ExecuteEditQuery("UPDATE Books SET Title =@param1 WHERE idBook =@param2", sqlParameters);
//SqlParameter[] sqlParameters = new SqlParameter[1]
//{
//    new SqlParameter ("@param1",author),
//};

SqlParameter[] myparm = new SqlParameter[1];
myparm[0] = new SqlParameter("@Author", SqlDbType.NVarChar, 200);
myparm[0].Value = author;

String query = @"SELECT * FROM Books  WHERE Author =@Author";
DataTable dt = ExecuteSelectQuery(query, myparm);

for (int i = 0; i < dt.Rows.Count; i++)
{
    Console.WriteLine(dt.Rows.ToString());
}
Console.Write("");

1

【问题讨论】:

  • adapter 未在您发布的代码中的任何地方定义? - command.ExecuteNonQuery(); 不应该存在,删除它,SqlCommand 实现 IDisposable 所以应该在 using 块内。

标签: c# sqlcommand mysql-parameter


【解决方案1】:

这是对您的方法的正确重写。

protected DataTable ExecuteSelectQuery(String query, params SqlParameter[] sqlParameters)
{
    using (SqlCommand command = new SqlCommand())    
        try
        {
            command.CommandText = query;
            command.Parameters.AddRange(sqlParameters);
            command.Connection = OpenConnection();

            DataTable dataTable = new DataTable();
            using (SqlDataAdapter adapter = new SqlDataAdapter(command))
                adapter.Fill(dataTable);
            return dataTable;
        }
        catch (SqlException e)
        {
            return null;
            throw new Exception("Error :" + e.Message);
        }
        finally
        {
            CloseConnection();
        }
}

注意SqlDataAdapter可以通过Open()Close()单独连接,如果SqlConnectionFill被调用时是Closed

【讨论】:

  • 如果您已经在 catch 中抛出异常,这将停止执行,那么拥有 return null; 有什么意义?由于方法首先存在,因此似乎无法访问异常?
  • @Symon 从问题中复制,是的,现在无法访问。它还应该包含SqlException 作为InnerException,并且可能使用ApplicationException 而不是Exception 基类。
  • 谢谢你的解释。现在,如果我想调用此方法并为其提供参数,我该怎么做?就像我准备了一个查询和参数列表,但我不知道该怎么做。
  • @user3560798 像在你的问题中那样称呼它,var resultTable = ExecuteSelectQuery(query, parameters);
【解决方案2】:

你的 OpenConnection() 方法是否返回一个连接对象。这可能会导致错误,没有给出方法的实现。代码中也没有定义适配器,如果没有初始化,也可能是错误的原因。

我想对你的代码说几句话:

1) 你有不必要的 command.ExecuteNonQuery(); ExecuteSelectQuery 方法中的语句。

2)DataAdapter可以直接填充DataTable,不必使用DataSet。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-06
    • 1970-01-01
    • 1970-01-01
    • 2013-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-12
    相关资源
    最近更新 更多