保留来自 dataReader c# 的 int 变量值
Posted
技术标签:
【中文标题】保留来自 dataReader c# 的 int 变量值【英文标题】:Keep int variables values from dataReader c# 【发布时间】:2021-01-05 20:43:40 【问题描述】:我对 C# 没有太多经验,但我正在尝试制作一个简单的带有个人财务的 Windows 窗体应用程序。 所以,我有 2 个 dataReader(我正在使用 Oracle 提供程序)和 sql(oracle 表)命令,它们只从表中选择 2 列,只有 1 个值,主要是收入 1 和收入 2 以及来自 a 的所有值的总和特定月份。
sql 字符串如下所示:
strSQL_sel_income1 = "select DISTINCT categorie,SUM(suma) from financiar where main_categ='income' and categorie IN ('income1') and EXTRACT(month FROM data)=" + luna_income + " Group by categorie";
strSQL_sel_income2 = "select DISTINCT categorie,SUM(suma) from financiar where main_categ='income' and categorie IN ('Income2') and EXTRACT(month FROM data)=" + luna_income + " Group by categorie";
“luna_income”值取自我选择特定月份的组合框。 问题是当我尝试从数据读取器获得的值中声明一个 Int 变量时,这些变量不会保留在 while 语句之外...... dr_income1/2 是 dataReader
if (dr_income1.HasRows)
while (dr_income1.Read())
label26.Text = dr_income1.GetString(0) + ": " + dr_income1.GetInt32(1) + "\n";
int suma_income1 = dr_incomei1.GetInt32(1);
else
label26.Text = "No info;
所以,我有两个相似的数据读取器和两个 int 变量 suma_income1 和 suma_income2。如果我尝试对它们求和,在WhIle 代码之外,我得到一个零值。我应该在哪里声明这两个变量以及如何保持它们的值?
int suma_income_total = suma_income1 + suma_income2;
label29.Text = "Income total: " + suma_income_total;
suma_income_total 为零!!!
dr_income1 = cm1.ExecuteReader();
dr_income2 = cm2.ExecuteReader();
label26.Text = "";
label28.Text = "";
if (dr_income1.HasRows)
while (dr_income1.Read())
label26.Text = dr_income1.GetString(0) + ": " + dr_income1.GetInt32(1) + "\n";
int suma_income1 = dr_income1.GetInt32(1);
else
label26.Text = "No info";
if (dr_income2.HasRows)
while (dr_income2.Read())
label28.Text = dr_income2.GetString(0) + ": " + dr_income2.GetInt32(1) + "\n";
int suma_income2 = dr_income2.GetInt32(1);
else
label28.Text = "no info";
int suma_income_total = suma_income1 + suma_income2;
label29.Text = "income total: " + suma_income_total;
dr_income2.Close();
dr_income1.Close();
【问题讨论】:
请您发布带有 2 个数据阅读器的完整数据阅读器代码。我只能看到一个数据读取器。 我编辑了第一篇文章,并添加了两个数据阅读器!谢谢! 【参考方案1】:我对您的代码进行了一些更改。这并不理想,因为有几种简单的方法。但它可以作为解决方法:
dr_income1 = cm1.ExecuteReader();
dr_income2 = cm2.ExecuteReader();
label26.Text = "";
label28.Text = "";
var suma_income1 =0;
var suma_income2 =0;
if (dr_income1.HasRows)
while (dr_income1.Read())
label26.Text = dr_income1.GetString(0) + ": " + dr_income1.GetInt32(1) + "\n";
suma_income1 += dr_income1.GetInt32(1);
else
label26.Text = "No info";
if (dr_income2.HasRows)
while (dr_income2.Read())
label28.Text = dr_income2.GetString(0) + ": " + dr_income2.GetInt32(1) + "\n";
suma_income2 += dr_income2.GetInt32(1);
else
label28.Text = "no info";
int suma_income_total = suma_income1 + suma_income2;
label29.Text = "income total: " + suma_income_total;
dr_income2.Close();
dr_income1.Close();
【讨论】:
@Livix 如果这个答案对你有帮助,你可以vote on / accept it。以上是关于保留来自 dataReader c# 的 int 变量值的主要内容,如果未能解决你的问题,请参考以下文章
C# - 将 DataReader 转换为 DataTable