user3275519
user3275519

Reputation: 19

Data Connection Establishment in c# using Access 2012

I am creating a Data Connection for my c# application using access 2010 and visual studio 2012. Though I searched about a code on the web and I got something like:

private void button1_Click(object sender, EventArgs e)
    {

        string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;
  Data Source= " + Application.StartupPath + @"\a.accdb;Persist Security Info=False";

  string queryString = @"SELECT userid, password FROM access WHERE userid =" + textBox1.Text + "";

  int found = 0; //0 means not found 1 means found

  using (OleDbConnection connection = new OleDbConnection(connectionString))
  {
      OleDbCommand command = new OleDbCommand(queryString, connection);
      //we open the database
      connection.Open();
      //we execute the previous query
      OleDbDataReader reader = command.ExecuteReader();

      //this loop will stop until all the rows found have been read
      while (reader.Read())
      {
          found = 1;
          Form5 o = new Form5();
          o.Show();
          this.Hide();

      }
      if (found == 0)


          MessageBox.Show("Please enter a valid username and password");


      reader.Close();
  }

}

but now I am getting an error with the same code as:

no value given for one or more required parameters

I have no idea about it. Please suggest me a way out of this error or suggest me some other complete way to use database connectivity for a login page.

Upvotes: 1

Views: 623

Answers (1)

Gord Thompson
Gord Thompson

Reputation: 123829

PASSWORD is a reserved word in Access SQL so you need to enclose it in square brackets, like this

string queryString = @"SELECT userid, [password] FROM ...

Edit re: comment

There's another problem with your query that stems from the fact that userid is (presumably) a text field. Try using a parameterized query instead:

string queryString = @"SELECT userid, [password] FROM access WHERE userid = ?";

int found = 0; //0 means not found 1 means found

using (OleDbConnection connection = new OleDbConnection(connectionString))
{
    OleDbCommand command = new OleDbCommand(queryString, connection);
    command.Parameters.AddWithValue("?", textBox1.Text);
    //we open the database
    connection.Open();
    //we execute the previous query
    OleDbDataReader reader = command.ExecuteReader();

Upvotes: 2

Related Questions