由于对象的当前状态,操作无效。 在C#中
我创建了这个方法来检查表中的这个记录的数量,但是当count(*)的值为0时,它给了我这个错误信息我使用这个库来连接oracle数据库
使用Oracle.DataAccess.Client;
private int checkPort(int portID)
{
int intCount = 0;
try
{
OracleCommand oraCommand = new OracleCommand();
oraCommand.Connection = new DBManager().getConnection();
oraCommand.CommandText = "select count(*) as num from wireless_port_oid where port_id=:port_id";
oraCommand.Parameters.Add(":port_id", portID);
OracleDataReader Reader= oraCommand.ExecuteReader();
return intCount;
while (**Reader.Read()**)//it gives exception here
//The err Operation is not valid due to the current state of the object.
{
intCount =Convert.ToInt32(Reader[0]);
Reader.Close();
oraCommand.Connection.Close();
oraCommand = null;
if (intCount > 0)
{
return 1;
}
}
Reader.Close();
Reader.Dispose();
oraCommand.Connection.Close();
oraCommand.Connection.Dispose();
oraCommand.Dispose();
return 0;
}
catch (OracleException exception)
{
Console.WriteLine(exception.Message);
return 0;
}
}
您在Count = 0时关闭阅读器,然后尝试在while循环中再次阅读它。
while (Reader.Read())//it gives exception here
//The err Operation is not valid due to the current state of the object.
{
intCount =Convert.ToInt32(Reader[0]);
Reader.Close();
oraCommand.Connection.Close();
oraCommand = null;
if (intCount > 0)
{
return 1;
}
// if intCOunt == 0 then what? loop again
}
但是你的代码是无效的 - 我只注意到你有一个返回intCount; 就在你说的那一行有错误之前。 我假设这只是一个例子错字。
我会重构你的代码以利用C#的using语句:
private int checkPort(int portID) {
string sql = "select count(*) as num from wireless_port_oid where port_id=:port_id";
int intCount = 0;
try {
using(OracleCommand oraCommand = new OracleCommand()) {
using(oraCommand.Connection = new DBManager().getConnection()) {
oraCommand.CommandText = sql;
oraCommand.Parameters.Add(":port_id", portID);
intCount = oraCommand.ExecuteScalar();
}
}
}
catch (OracleException exception) {
Console.WriteLine(exception.Message);
// may be you shouldn't return 0 here possibly throw;
}
return intCount;
}
链接地址: http://www.djcxy.com/p/61541.html
上一篇: Operation is not valid due to the current state of the object. in C#
下一篇: Git local mirror