问题
When I try to assign the reader C# throws an exception:
Invalid operation. The connection is closed
I try to get a result from a query that returns a single cell with an average value inside. cmd is an oraclecomand that i use to insert a row into a table and so far so good. I see the message box next and after that the exception appears.
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);
}
回答1:
When you use `OracleCommand', you have to associate a valid OracleConnection object to it.
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);
}
}
Hope this help.
Thanks.
回答2:
You should open the connection and you should also use sql-parameters. Hopefully this is the correct oracle syntax because i cannot test it:
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();
}
}
}
}
Note that i have used the using
-statement to ensure that all unmanaged resources are disposed as soon as possible. It also closes connections (even on error).
Edit: Since you are selecting just a single value i suggest to use 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();
}
}
来源:https://stackoverflow.com/questions/17062954/error-with-oracledatareader-error-invalid-operation-the-connection-is-closed