描述不基于数据库

时间:2013-08-16 07:30:09

标签: c# database winforms

我可以从数据库中检索数据并且现在可以正常工作,但只能在第一行( description code 都是正确的,并且基于数据库)。< / p>

在第二行, description 不是基于数据库,但它显示第一行的 description ,即使第一行和第二行的代码是不同的。我该如何解决这个问题?

以下是一些代码:

private void UpdateDatas()
{
  int codeValue = 0;

  OleDbDataReader dReader;
  OleDbConnection conn = new OleDbConnection(connectionString);
  conn.Open();
  OleDbCommand cmd = new OleDbCommand(
    "SELECT [Description], [Price] FROM [Data] WHERE [Code]=@Code", conn);

  cmd.Parameters.Add("Code", System.Data.OleDb.OleDbType.Integer);
  cmd.Parameters.Add("Code", System.Data.OleDb.OleDbType.Integer);

  if (int.TryParse(this.textBoxCodeContainer[0][0].Text, out codeValue))
  {
    cmd.Parameters["Code"].Value = codeValue;
  }
  else if (int.TryParse(this.textBoxCodeContainer[0][1].Text, out codeValue))
  {
    cmd.Parameters["Code"].Value = codeValue;
  }
  else
  {
    MessageBox.Show("Error");
  }

  dReader = cmd.ExecuteReader();

  while (dReader.Read())
  {
    if (textBoxCodeContainer[0][0].TextLength != 0)
    {
      this.textBoxDescContainer[0][0].Text = dReader["Description"].ToString();
      this.textBoxSubTotalContainer[0][0].Text = dReader["Price"].ToString();
    }

    if (textBoxCodeContainer[0][1].TextLength != 0)
    {
      this.textBoxDescContainer[0][1].Text = dReader["Description"].ToString();
      this.textBoxSubTotalContainer[0][1].Text = dReader["Price"].ToString();
    }
  }

  dReader.Close();
  conn.Close();
 }

这是图片: code in the first line is "0002" and the description for it is "B", this is correct (based on database), but code in the second line is "0005", and the description for it supposed to be "E", but this is show "B", it is like copy the description in the first line, even though code is different

这是数据库的图像: enter image description here

1 个答案:

答案 0 :(得分:1)

这是因为你在循环中为两个文本框处理了第一个记录两次。试试这个作为快速解决方法:

int index = 0;
while (dReader.Read())
{
  if (textBoxCodeContainer[0][index].TextLength != 0)
  {
    this.textBoxDescContainer[0][index].Text = dReader["Description"].ToString();
    this.textBoxSubTotalContainer[0][index].Text = dReader["Price"].ToString();
  }

  index += 1;
}

第二个问题是,您在查询中为一个参数(代码)添加了两个值,因此select的结果将只包含一行。你应该使用“IN”SQL关键字。第二个快速修复将涉及您的查询:

var query = "SELECT [Description], [Price] FROM [Data] WHERE [Code] IN (";

 if (int.TryParse(this.textBoxCodeContainer[0][0].Text, out codeValue))
 {
 query = query + codeValue.ToString();
 }
 if (int.TryParse(this.textBoxCodeContainer[0][1].Text, out codeValue))
 {
 query = query + "," + codeValue.ToString();
 }

 query = query + ")";

 OleDbCommand cmd = new OleDbCommand(query, conn);
 dReader = cmd.ExecuteReader();

如何使用“IN”子句对查询进行参数化是另一个问题 - 这只是一个快速解决方案,可以使其工作。

相关问题