1

当我尝试分配阅读器时,C# 抛出异常:

Invalid operation. The connection is closed

我尝试从返回单个单元格的查询中获取结果,其中包含平均值。cmd 是一个 oraclecomand,我用它来在表中插入一行,到目前为止效果很好。我接下来会看到消息框,然后出现异常。

          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);
            }
4

2 回答 2

3

您应该打开连接,还应该使用 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-statement 来确保尽快处理所有非托管资源。它还会关闭连接(即使出现错误)。

编辑:由于您只选择一个值,我建议使用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();
    }
}
于 2013-06-12T10:21:37.580 回答
1

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

  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);
                    }
   }

希望这有帮助。

谢谢。

于 2013-06-12T10:24:37.663 回答