簡體   English   中英

連接錯誤C#

[英]Connection error C#

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

我整個下午都在努力解決這個問題,但我不能這樣來這里尋求幫助

我認為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);
     //....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM