2016-08-16 111 views
0

dt.Rows.Count的值始终等于1,并且dt.Rows [0] [0]和dt.Rows [0] [ 1]是空字符串,当我查询没有记录的sqlStr。C#数据表行值为空字符串,但存在空值

但我在数据库中执行sqlStr。它是空的。 Here is the database screenshot 我不知道它为什么。

string sqlStr = "select SUM(userIncome),SUM(userSpend) from tb_billlist where userPhone = '" + userPhone + "' and " + 
    "billTime between '" + beginDate + "' and '" + endDate + "'"; 
//execute sql 
DataTable dt = new DataTable(); 
dt = MysqlHelper.ExecuteDataTable(sqlStr); 
if (dt.Rows.Count > 0) 
{ 
    userBillInfo.userAllIncome = (float.Parse)(dt.Rows[0][0].ToString()); 
    userBillInfo.userAllSpend = (float.Parse)(dt.Rows[0][1].ToString()); 
} 
else 
{ 
    userBillInfo.userAllIncome = 0; 
    userBillInfo.userAllSpend = 0; 
} 
+0

看起来像没有行.. – BugFinder

+2

我会*开始*通过修复SQL注入攻击漏洞(或至少是转换脆弱性,至少)你去那里。使用参数化SQL,* always *。 –

+0

因为SUM()总是返回一些东西,所以你总会得到一行。 –

回答

-1

为了实现这个目标,你可以改变你的查询,如果“空值的总和”的情况下,返回值为0:

string sqlStr = "select COALESCE(SUM(userIncome), 0), COALESCE(SUM(userSpend), 0) from tb_billlist where userPhone = '" + userPhone + "' and " + 
    "billTime between '" + beginDate + "' and '" + endDate + "'"; 
//execute sql 
... 

因此,你将有0作为返回值为田野。

+0

Thanks^_ ^它工作!我发现IFNULL的作用与MySQL中的COALESCE相同。 – figureout77

+0

是的,IFNULL也可以使用! – Alvimar

相关问题