这是我使用的代码,用于根据Class字段值选择最大的。但是当表中没有关于类字段的数据时。然后产生错误。
using (var conn = new OleDbConnection(DatabaseObjects.ConnectionString))
{
conn.Open();
command = new OleDbCommand("select max(RollNo) as Roll from Students where Class = '"+cmbClass.Text+"'", conn);
OleDbDataReader dr = command.ExecuteReader();
if (!dr.IsDBNull(0))
{
while (dr.Read())
{
i = Convert.ToInt32(dr["Roll"]);
}
}正在发生InvalidOperation异常。如果表中有数据,我希望得到RollNo的值。如果表中没有可用的数据,那么我该怎么办?
发布于 2020-06-06 19:13:07
你正在逆转这些步骤:
试试这个:
while (dr.Read())
{
if (!dr.IsDBNull(0))
{
i = Convert.ToInt32(dr["Roll"]);
}
}当您只关注单个值时,请使用executeScalar获取值;
conn.Open();
command = new OleDbCommand("select isnull(max(RollNo),-1) as Roll from Students where Class = '"+cmbClass.Text+"'", conn);
int rollNo = (int) command.ExecuteScallar();
if(rollno !=-1)
{
// TODO :
}https://stackoverflow.com/questions/62236465
复制相似问题