C#MySQL和InvalidCastException

时间:2013-08-08 17:38:14

标签: c# mysql .net

我有一个查询,我尝试获取和值,但是我得到了InvalidCastException。

我的查询是:

SELECT e.clockNr,e.firstName,e.LastName,e.unionName,i.points 
FROM ( 
    SELECT employee.clockNr AS clockNr,
           employee.firstName AS firstName,
           employee.lastName AS lastName,
           Unions.name AS unionName 
           FROM employee,Unions 
           WHERE employee.active=1 AND employee.unionId = unions.id  
           GROUP BY employee.clockNr 
     ) e LEFT JOIN (
           SELECT infraction.clockNr AS clockNr, 
           CAST(SUM(Infraction.points) AS SIGNED) AS points 
           FROM infraction 
           WHERE infraction.infractionDate >=@startDate 
           AND infraction.infractionDate <=@endDate 
           GROUP BY infraction.clockNr 
     ) i ON e.clockNr = i.clockNr 
ORDER BY e.clockNr ASC

它出错的'点'列。 我已将CAST添加到SIGNED但这没有帮助。

我读出专栏的方式是:

int iGetPoints = Convert.ToInt32(reportReader["points"]);

也尝试过:

int iGetPoints = (int)reportReader["points"];

但两者都会引发InvalidCastException。 该查询在PHPMyAdmin中进行了测试并在那里正常工作。

任何人都可以看到我做错了什么或给我一个提示在哪里寻找?

1 个答案:

答案 0 :(得分:2)

因为points列是左连接的一部分,所以它可以为null。我假设这是问题所在。您需要测试null以避免强制转换异常:

// Note: this is for DataTableReader; see below for MySQL data reader
int iGetPoints = 0;
if (!reportReader.IsDBNull(reportReader.DBOrdinal("points"))) {
   iGetPoints = Convert.ToInt32(reportReader["points"]);
}

IsDBNull方法需要列名的索引(它不能与名称一起使用),因此调用DBOrdinal从名称中获取索引。


注意:上面的答案适用于“通用”System.Data.DataTableReader类,但不适用于MySQL数据阅读器。 Gerard在下面的评论中发布了MySQL阅读器所需的更改。他们是:

int iGetPoints = 0;
if (reportReader["points"] != DBNull.Value) {
   iGetPoints = Convert.ToInt32(reportReader["points"]);
}