我在此代码中有错误。应该发生的是,如果我在数据库中有两个摊位,摊位价格必须加倍,但是这个代码中发生的事情是,如果我在数据库中有两个摊位,摊位价格不会翻倍,如果我只有一个摊位摊位价格是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;
}
答案 0 :(得分:1)
我认为错误就在这里:
stallReader.Read();
while(stallReader.Read())
您阅读第一条记录,然后阅读第二条记录,而不处理第一条记录 您必须删除第一行并离开
while(stallReader.Read())
作为旁注,您应该尝试始终对实现using
接口的类使用IDisposable
语法。所以,只是一个例子:
using (OleDbConnection connection = new OleDbConnection())
{
// All the code inside
}
通过这种方式,您可以确定该对象已正确释放。
最后:不要手动撰写查询,而是使用参数!!
使用参数可以避免SQL注入和由于数字(浮点数,双精度,货币)和日期转换而引起的许多麻烦!!