Search code examples
c#sql.netms-accessoledb

System.Data.OleDb.OleDbException: Data type mismatch in criteria expression


This is my code:

OleDbCommand Cmd = new OleDbCommand();
Cmd.Connection = MyConn;
Cmd.CommandText = "SELECT * FROM catalogue WHERE id = '" + questionid + "'";

OleDbDataReader read = Cmd.ExecuteReader();

int id = 0;

while (read.Read())
{
    id = Convert.ToInt32(read["id"]);
}

Here's the error it gives me:

Line 27:         Cmd.CommandText = "SELECT * FROM catalogue WHERE id = '" + questionid + "'";
Line 28: 
Line 29:         OleDbDataReader read = Cmd.ExecuteReader(); // The error is here
Line 30: 
Line 31:         int id = 0;

I know there is also another question about the same issue on Stack Overflow, but it doesn't seem to solve my problem (it may solve yours, so I put a link).


Solution

  • Please learn about using blocks for all your disposibles, that includes database connection, command and readers.

    Your code is vulnerable to sql injection, you may want to fix that by using parameters.

    Finally, I suspect your id field in the database is of integer type, so using quotes around the value is a mistake. But please read up on parameters instead of fixing that. Parameters will get rid of that problem anyway.