gooseman1998
gooseman1998

Reputation: 11

Data type mismatch in criteria expression Oledb Access database

I'm getting the error:

Data type mismatch in criteria expression

When using this code. And using Access database.

OleDbConnection bab = new OleDbConnection();

bab.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\sdega\OneDrive\school\Werknemersdata.accdb;Persist Security Info=False;";

bab.Open();
try
{                  
    OleDbCommand kaas = new OleDbCommand();

    kaas.Connection = bab;
    kaas.CommandText = "insert into Werknemersdata (Naam, Adres, Postcode, Woonplaats, Salaris) values ('" + txtNaam.Text + "', '" + txtAdress.Text + "', '" + txtpostcode1.Text + " " +txtpostcode2.Text + "', '" + txtwoonplaats.Text + "', '" + txtsalaris.Text + "')  ";
    kaas.ExecuteNonQuery(); // this is where it goes wrong

    txtStatus.BackColor = Color.Green;

    MessageBox.Show("data saved");

    bab.Close();

}
catch (Exception ghakbal)
{
    MessageBox.Show("Error" + ghakbal);
}

Upvotes: 1

Views: 216

Answers (1)

Salah Akbari
Salah Akbari

Reputation: 39946

You missed one ' after '" + txtpostcode1.Text + " and one before " +txtpostcode2.Text + "' and also one , between them. It should be like this:

'" + txtpostcode1.Text + "' , '" +txtpostcode2.Text + "',

Also I strongly recommend that you always use parameterized queries to avoid SQL Injection. Like this:

kaas.CommandText = "insert into Werknemersdata (Naam, Adres, Postcode, Woonplaats, Salaris) values (?, ? ,.....");
kaas.Parameters.AddWithValue("Naam", txtNaam.Text);
kaas.Parameters.AddWithValue("Adres", txtAdress.Text);
//And other parameters...

Also It would be better to specify the type directly and use the Value property. Read more here.

Upvotes: 2

Related Questions