2015-11-04 83 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