【发布时间】:2016-04-07 22:34:32
【问题描述】:
我已经阅读了许多类似的问题并尝试了几种不同的方法,但我不明白为什么这不起作用。求和的列是 int 类型。我尝试过转换为 uint 和 int32。我很欣赏方向。谢谢你。
int i = 1;
int total=0;
while (i < 7)
{
string conString = @"Data Source=UATDB2\sqleuat;Initial Catalog=CVNee;User ID=appuser;Integrated Security=true";
SqlConnection connection = new SqlConnection(conString);
connection.Open();
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SELECT SUM(AMOUNT) FROM TRANSACTIONS_DETAIL2 WHERE TRANSACTIONS_DETAIL2.TRANS_TYPE =" + i + "AND TRANSACTIONS_DETAIL2.HOH_UPI = '185292000'";
int amt = ((int)cmd.ExecuteScalar());
//amt = cmd.ExecuteScalar();
if (i == 1)
{
total = total + amt;
}
if (i == 2)
{
total = total - amt;
}
if (i == 3)
{
total = total - amt;
}
if (i == 4)
{
total = total + amt;
}
if (i == 5)
{
total = total + amt;
}
if (i == 6)
{
total = total + amt;
}
connection.Close();
ViewBag.TotalBalance = total;
i++;
}
【问题讨论】:
-
如果SUM返回null,我想你会得到这样的错误。
-
是的,我也注意到了。我现在正在使用 Convert.ToInt32 并且我得到了一个更详细的异常。处理潜在空值的最佳方法是什么?
-
几乎总是与 SQL 相关的问题:不要使用字符串连接创建查询,而是使用参数化查询,因为它们会阻止 SQL 注入。
标签: c# sql-server asp.net-mvc-5