C# MySQL求和出现InvalidCastException异常

3

我有一个查询,试图获取总和值,但是我得到了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

问题出在“points”列上。 我已经将CAST添加到SIGNED,但这并没有帮助。

我读取该列的方式是:

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

也尝试了以下方法:

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

但是两者都引发了InvalidCastException异常。 该查询在PHPMyAdmin中进行了测试,并且在那里运行良好。

有没有人能看出我做错了什么,或者给我提示应该往哪里查找?


points列的数据类型是什么? - Sriram Sakthivel
这是一个整数(INT)。我刚试图将其解析为字符串,然后转换为整数,出于某种原因它起作用了。 - Gerard van den Bosch
1个回答

2

由于points列是左连接的一部分,因此它可能为空。我认为这就是问题所在。您需要测试是否为空以避免转换异常:

// 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"]);
}

这是一个好观点,只是MySQL数据读取器不熟悉DBOrdinal? - Gerard van den Bosch
这就是诀窍: int iGetPoints = 0; if (reportReader["points"] != DBNull.Value) { iGetPoints = Convert.ToInt32(reportReader["points"]); } - Gerard van den Bosch
谢谢Gerard,好棒的发现!我已经更新了我的答案,包括你提供的MySQL数据读取器代码;我认为很多人会从中受益 :) - Ed Gibbs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接