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

时间:2013-06-12 10:15:53

标签: c# winforms oracle

当我尝试分配阅读器时,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);
            }

2 个答案:

答案 0 :(得分: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语句确保尽快处理所有非托管资源。它还会关闭连接(即使出错)。

修改:由于您只选择一个值,我建议使用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();
    }
}

答案 1 :(得分: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);
                    }
   }

希望得到这个帮助。

感谢。