2013-10-23 37 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方法使用。