【问题标题】:How can I preempt a "Specified cast is not valid" exception?如何抢占“指定的强制转换无效”异常?
【发布时间】:2013-10-23 23:18:16
【问题描述】:

在 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;
}

...但它不起作用 - 我仍然收到“Specified cast is not valid”异常。

我如何安全地检查那里的空字符串/空值并忽略通过结果集的传递,以便获得后续记录?

或者我可以通过更改 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

【问题讨论】:

  • 你需要处理DBNull

标签: sql ms-access casting null oledbdatareader


【解决方案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

【讨论】:

    【解决方案2】:

    有时需要更改 OleDbDataReader 中使用的数据类型方法,如以下代码和 cmets 所示:

    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 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-20
      • 1970-01-01
      • 2019-03-27
      • 2012-09-21
      • 1970-01-01
      • 1970-01-01
      • 2018-05-27
      相关资源
      最近更新 更多