OracleDataReader错误.错误:无效操作.连接已关闭

本文关键字:错误 连接 操作 无效 OracleDataReader | 更新日期: 2023-09-27 18:18:05

当我尝试分配reader时,c#抛出异常:

Invalid operation. The connection is closed

我试图从一个查询中得到一个结果,该查询返回一个单元格内的平均值。CMD是一个oraclec命令,我用它来插入一行到表中,到目前为止还不错。我接下来看到消息框,然后出现异常。

          try
            {
                cmd.ExecuteNonQuery();
                MessageBox.Show("Recipe Rated");
                OracleCommand cm = new OracleCommand("select round(avg(rating),1) from rates where id_rec = "+id);
                OracleDataReader reader = cm.ExecuteReader();
                reader.Read();
                textBox5.Text =""+reader.GetInt16(0);
            }

OracleDataReader错误.错误:无效操作.连接已关闭

应该打开连接,并且还应该使用sql-parameters。希望这是正确的oracle语法,因为我不能测试它:

using(var con = new OracleConnection("ConnectionString Here"))
using(var cmd = new OracleCommand("ADD YOUR INSERT/UPDATE/DELETE", con))
{
    con.Open();
    cmd.ExecuteNonQuery();
    using (var cm = new OracleCommand("select round(avg(rating),1)As AvgRating from rates where id_rec = @id", con))
    {
        cm.Parameters.AddWithValue("@id", id);
        using (var reader = cm.ExecuteReader())
        {
            if (reader.Read())
            {
                textBox5.Text = reader.GetInt16(0).ToString();
            }
        }
    }
}

请注意,我已经使用using -语句来确保所有非托管资源都被尽快处置。它还关闭连接(即使在错误时)。

编辑:由于您选择的只是一个值,我建议使用ExecuteScalar:

using (var cm = new OracleCommand("select round(avg(rating),1)As AvgRating from rates where id_rec = @id", con))
{
    cm.Parameters.AddWithValue("@id", id);
    object avgRating = cm.ExecuteScalar();
    if (!(avgRating is DBNull))
    {
        textBox5.Text = avgRating.ToString();
    }
}

当你使用' oracleccommand '时,你必须将一个有效的oraclecconnection对象关联到它。

  using (OracleConnection connection = new OracleConnection(connectionString))
    {
                   MessageBox.Show("Recipe Rated");
                   OracleCommand cm = new OracleCommand("select round(avg(rating),1) from rates where id_rec = "+id);
                   try
                    {
                        cm.Connection = connection;
                        connection.Open(); //oracle connection object
                        OracleDataReader reader = cm.ExecuteReader();
                        reader.Read();
                        textBox5.Text =""+reader.GetInt16(0);
                    }
   }

希望有帮助。

谢谢。