gpt4 book ai didi

c# - 由于对象的当前状态,操作无效。在 C#

转载 作者:太空狗 更新时间:2023-10-29 19:39:38 24 4
gpt4 key购买 nike

我创建了这个方法来检查表中这条记录的数量但是当 count(*) 的值为 0 时,它会给我这个错误信息我使用这个库来连接 oracle db

使用 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
}

但是您的代码无效 - 我刚刚注意到您有一个 return 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;
}

关于c# - 由于对象的当前状态,操作无效。在 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11490855/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com