2013-10-23 43 views
0

在Web API應用程序中查詢MS Access數據庫時,如果我試圖將空字符串分配給變量,則會出現「指定的轉換無效」異常。 IOW,當這個代碼:如何搶佔「指定的演員無效」異常?

var accountID = oleDbD8aReader.GetInt16(0); 
var platypusName = oleDbD8aReader.GetString(1); 

...達到一個記錄,其中結果集中的第二列包含空/空字符串,它炸彈。

所以,我想我可以在通這樣的領導該關:

string platypusName; 
var accountID = oleDbD8aReader.GetInt16(0); 
if (!string.IsNullOrEmpty(oleDbD8aReader.GetString(1))) 
{ 
    platypusName = oleDbD8aReader.GetString(1); 
} 
else 
{ 
    platypusName = string.Empty; 
} 

...但它不工作 - 我仍然得到「指定的轉換是無效」異常。

如何安全地檢查空字符串/空值,並忽略通過結果集,以便它將獲得後續記錄?

或者我可以通過更改SQL語句排除結果集中的空/空字符串來排除這種情況嗎?如果是這樣,怎麼樣?查詢的格式如下:

SELECT td_duckbill_accounts.platypus_no, t_accounts.name 
FROM t_accounts 
INNER JOIN td_duckbill_accounts ON t_accounts.account_no = td_duckbill_accounts.account_no  
ORDER BY td_duckbill_accounts.platypus_no 
+1

你需要處理'DBNull'。 –

回答

1

我認爲有查詢返回空字符串是簡單的解決方案:

SELECT td_duckbill_accounts.platypus_no, 
     IIF(ISNULL(t_accounts.name),'',t_accounts.name) AS name 
FROM t_accounts 
INNER JOIN td_duckbill_accounts ON t_accounts.account_no = td_duckbill_accounts.account_no  
ORDER BY td_duckbill_accounts.platypus_no 

這也應該工作,但現在我不能測試:

SELECT td_duckbill_accounts.platypus_no, 
     Nz(t_accounts.name,'') AS name 
FROM t_accounts 
INNER JOIN td_duckbill_accounts ON t_accounts.account_no = td_duckbill_accounts.account_no  
ORDER BY td_duckbill_accounts.platypus_no 
0

有時需要更改OleDbDataReader中使用的數據類型方法,因爲此代碼和註釋顯示:

while (oleDbD8aReader != null && oleDbD8aReader.Read()) 
{ 
    string accountId = oleDbD8aReader.GetString(0); 
    string accountName = oleDbD8aReader.GetString(1); 
    //int useOnItems = oleDbD8aReader.GetInt32(2); <= get "specified cast not valid" with Int32 
    int useOnItems = oleDbD8aReader.GetInt16(2); // This works 
    expenses.Add(new Expense { account_id = accountId, name = accountName, use_on_items = useOnItems }); 
} 

底層表中的數據類型是Integer,所以我猜想LongInteger(另一個Access整數類型)GetInt32()將是OleDbDataReader方法使用。