0
private OleDbConnection conexao;
private Timer time = new Timer();

public void Conexao() //Conexão
{
   string strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|DB.accdb";
   conexao = new OleDbConnection(strcon);
}

void tabela()
{
   Conexao();
   conexao.Open();
   label1.Text = DateTime.Now.ToString();
   string bn = "select D2 from Planilha where D2='" + label1.Text + "'";
   textBox1.Text = label1.Text;
   OleDbCommand Queryyy = new OleDbCommand(bn, conexao);
   OleDbDataReader drr;
   drr = Queryyy.ExecuteReader();
   if (drr.Read() == true)
   {
      try
      {
         MessageBox.Show("Hi");
      }
      catch (OleDbException ex)
      {
         MessageBox.Show("" + ex);
      }
   }
}

private void timer1_Tick(object sender, EventArgs e)
{
   tabela();
}

定时器间隔 = 1000

(点击查看大图)
http://i.stack.imgur.com/2g8QA.png

我整个下午都在尝试修复它但无法解决所以我来这里寻求帮助

4

1 回答 1

2

我认为asawyer 的评论是对的,我敢打赌,问题在于您没有正确处理对象,摆脱了类对象并使用using语句

public OleDbConnection Conexao() //Conexão
{
   string strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|DB.accdb";
   return new OleDbConnection(strcon);
}

void tabela()
{
    try
    {    
        timer1.Enabled = false;
        using(var conexao = Conexao())
        {   
           conexao.Open();
           label1.Text = DateTime.Now.ToString();
           string bn = "select D2 from Planilha where D2='" + label1.Text + "'";
           textBox1.Text = label1.Text;
           using(OleDbCommand Queryyy = new OleDbCommand(bn, conexao))
           using(OleDbDataReader drr = Queryyy.ExecuteReader())
           {
               if (drr.Read() == true)
               {
                  try
                  {
                     MessageBox.Show("Hi");
                  }
                  catch (OleDbException ex)
                  {
                     MessageBox.Show("" + ex);
                  }
               }
           }
        }
    }
    finally
    {
        timer.Enabled = true;
    }
}

private void timer1_Tick(object sender, EventArgs e)
{
   tabela();
}

同样从您只读取第一行的第一列的事实来看,您应该使用ExecuteScalar而不是ExecuteReader.

using(OleDbCommand Queryyy = new OleDbCommand(bn, conexao))
{
   try
   {
       var result = Queryyy.ExecuteScalar();
       if (result != null)
       {
          MessageBox.Show("Hi");
       }
    }
    catch (OleDbException ex)
    {
       MessageBox.Show("" + ex);
    }
   }
}

您还应该使用参数化查询。

  label1.Text = DateTime.Now.ToString();
  string bn = "select D2 from Planilha where D2=@param1";
  textBox1.Text = label1.Text;
  using(OleDbCommand Queryyy = new OleDbCommand(bn, conexao))
  {
     Queryyy.Parameters.AddWithValue("@param1", label1.Text);
     //....
于 2013-11-13T22:48:38.537 回答