c# - 我需要在我的代码中添加 int 变量,有什么想法吗?
问题描述
private void button1_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("select * from package where pkgid = '" + txtpkgid.Text + "' ", con);
con.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
int HC = Convert.ToInt32(dr["HC"]);
int KC = Convert.ToInt32(dr["KC"]);
int DC = Convert.ToInt32(dr["DC"]);
int DONR = Convert.ToInt32(dr["DONR"]);
int VNPR = Convert.ToInt32(dr["VNPR"]);
}
con.Close();
cmd = new SqlCommand("select * from vehicle where RegistrationNo = '" + txtcarid.Text + "' ", con);
con.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
int VDP = Convert.ToInt32(dr["VDP"]);
}
con.Close();
}
如何添加以上内容?
抱歉,我是初学者,所以这可能看起来很愚蠢,非常感谢任何有关如何将它们添加在一起的帮助。
基本上我想得到 Result = HC+KC+DC+DONR+VNPR+VDP 并在标签中显示结果。
问题是我不知道如何将 VDP 的价值带出来。
解决方案
这些方面的东西:
long result = 0;
while (dr.Read())
{
result += Convert.ToInt32(dr["HC"]);
result += Convert.ToInt32(dr["KC"]);
result += Convert.ToInt32(dr["DC"]);
result += Convert.ToInt32(dr["DONR"]);
result += Convert.ToInt32(dr["VNPR"]);
}
con.Close();
请注意,您应该正确处理命令和读取器对象。正如其他评论者指出的那样,您可以在 SQL 端计算此总和,因此您不必遍历结果集。如果您继续使用客户端迭代器,还记得添加适当的 NULL 处理,以防 dr[...] 可以返回 a null
or DBNull.Value
。
推荐阅读
- tkinter - 何时以及为什么需要将窗口坐标更改为画布坐标?
- vb.net - 试图在函数头中使用类型类型的变量 - 包含类型
- python - 从 Python 与 Node.js 进程通信
- php - php `require()` 一个包含另一个 `require()` 的文件
- python - 在 Heroku 上将自然语言工具包与 Django 结合使用 - - 错误:找不到“nltk.txt”
- r - list.files:正则表达式模式在 Windows 上不起作用?
- migration - 在现有物理主机上无法增加虚拟机容量时,配置虚拟机到另一台物理主机的实时迁移策略
- c++ - 计算复合类的哈希值
- swift - 在使用 Swift 而没有第三方框架的情况下查看生产中抛出的错误的好方法是什么?
- c++ - 正确使用函数的显式模板实例化?