价值没有';t加倍
本文关键字:加倍 | 更新日期: 2023-09-27 18:30:01
我在这段代码中有错误。应该发生的情况是,如果我在数据库中有两个摊位,摊位价格必须翻倍,但在这段代码中发生的是,如果数据库中有二个摊位,则摊位价格不会翻倍,如果我只有一个摊位,那么摊位价格为0。
public double GetStallPrice(int commtaxno)
{
try
{
string query = "SELECT * FROM contract_details WHERE comm_tax_no = " + commtaxno;
DatabaseString myConnectionString = new DatabaseString();
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = myConnectionString.connect();
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = query;
OleDbDataReader stallReader = command.ExecuteReader();
stallReader.Read();
while(stallReader.Read())
{
try
{
string query2 = "SELECT section_ID FROM specific_stall WHERE stall_no = '" + stallReader["stall_no"].ToString() + "'";
OleDbCommand command2 = new OleDbCommand();
command2.Connection = connection;
command2.CommandText = query2;
OleDbDataReader sectionReader = command2.ExecuteReader();
sectionReader.Read();
sectionid = Convert.ToInt32(sectionReader["section_ID"].ToString());
try
{
string query3 = "SELECT stall_price FROM stall_sections WHERE section_ID = " + sectionid;
OleDbCommand command3 = new OleDbCommand();
command3.Connection = connection;
command3.CommandText = query3;
OleDbDataReader stallPriceReader = command3.ExecuteReader();
stallPriceReader.Read();
stall_price = Convert.ToDouble(stallPriceReader["stall_price"].ToString());
}
catch (Exception c)
{
MessageBox.Show(c.GetBaseException().ToString());
}
}
catch (Exception b)
{
MessageBox.Show(b.GetBaseException().ToString());
}
sum_stall_price = sum_stall_price + stall_price;
}
connection.Close();
}
catch (Exception a)
{
MessageBox.Show(a.GetBaseException().ToString());
}
return sum_stall_price;
}
我认为错误在这里:
stallReader.Read();
while(stallReader.Read())
您先读取第一条记录,然后再读取第二条记录,而不处理第一条记录
你必须删除第一行,只留下
while(stallReader.Read())
附带说明一下,您应该尝试在实现IDisposable
接口的类中始终使用using
语法。所以,举个例子:
using (OleDbConnection connection = new OleDbConnection())
{
// All the code inside
}
通过这种方式,您可以确保对象已正确释放。
最后:不要手动编写查询,而是使用参数
使用参数可以避免SQL注入和由于数字(浮点、双精度、货币)和日期转换而带来的许多麻烦!!