c#访问数据库读取错误

时间:2016-03-13 16:44:45

标签: c# ms-access

我想用这段代码从数据库中读取。

private void button1_Click(object sender, EventArgs e)
{
    connection.Open();

    OleDbCommand parancs = new OleDbCommand();
    parancs.Connection = connection;
    parancs.CommandText= "select * from table where Nev='"+textBox1.Text+"' and Jelszo='"+textBox2.Text+"'";

    OleDbDataReader olvas = parancs.ExecuteReader();
    MessageBox.Show("SIKERES BEJELENTKEZES");
    connection.Close();
}

但是我收到了这个错误:

  

未处理的类型' System.Data.OleDb.OleDbException'发生在System.Data.dll

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

首先关闭connection未定义

你想真正使用using围绕所有这些使它变得更好,并在完成后为你关闭连接。使用创建对象的using statement block关闭,刷新和处理,然后允许其他进程再次使用资源。这可确保框架为每个流程采取最佳措施。

以下操作只需确保在其中设置连接字符串。

private void button1_Click(object sender, EventArgs e)
{
    using(SqlConnection conn = new SqlConnection()) 
    {
       conn.ConnectionString = "your connection_string";
       conn.Open();

      // Create the command
      SqlCommand command = new SqlCommand("select * from table where Nev= @firstParmeter and Jelszo= @secondParameter", conn);
      // Add the parameters.
      command.Parameters.Add(new SqlParameter("firstParmeter", textBox1.Text));
      command.Parameters.Add(new SqlParameter("secondParameter", textBox2.Text));

      // Create new SqlDataReader object and read data from the command.
      using (SqlDataReader reader = command.ExecuteReader())
      {
        // while there is another record present
        while (reader.Read())
        {
            // set what you want here as it will be reading all the rows from the query example below
            // write the data on to the screen
            Console.WriteLine(String.Format("{0} \t | {1} \t | {2} \t | {3}",
            // call the objects from their index
            reader[0], reader[1], reader[2], reader[3]));

        }
      }
    }
}