2015-11-04 38 views
2

我使用Sqlite作为后端和Windows窗体应用程序(C#)作为前端。如何检查datareader是否为空或错误 - 错误

我要通过这个代码:

cmdgetTransaction_ID = new SQLiteCommand("SELECT MAX(transaction_id) as expr1 FROM transaction_master WHERE transaction_id LIKE '"+temp+"%' ", con); 
SQLiteDataReader reader = cmdgetTransaction_ID.ExecuteReader(); 
if (reader["expr1"]!=DBNull.Value) 
{ 
    name= reader.GetString(0); 
    string[] substrings = System.Text.RegularExpressions.Regex.Split(name, "([a-z]+)|([0-9]+)"); 
    MessageBox.Show(substrings[0]); 
} 
else 
{ 
    name=name+temp+"1"; 
    lblTranID.Text = name; 
} 

我也试过这样:if (reader.IsDBNull(0))

在调试(步到),它报告以下情况除外:

第一次机会System.Data.SQLite.dll中发生类型'System.InvalidOperationException'异常

我不知道我在做什么错误,以便它会产生一个异常。

+0

要么你头衔是误导或内容。你想检查读者是否有行或个别列为空? – niksofteng

+0

错误发生在哪条线上? – Steve

+0

检查这个http://stackoverflow.com/questions/4393092/c-sharp-a-first-chance-exception-of-type-system-invalidoperationexception –

回答

1

这应该为你工作:

if (reader != null && reader.HasRows) 
{ 
    while (reader.Read()) 
    { 
     ... 
    } 
} 
+0

问题仍然存在:尽管数据读取器不包含任何记录,但条件变为true,它会进入while循环,因为没有数据会引发异常 - 我已附加屏幕镜头 – user2130649

+0

当'while'行或之后当您尝试读取'expr1'列时,它会引发异常吗?也不要编辑发布自己的屏幕截图的答案。改为使用评论。 – niksofteng