c# – Query an Access database from C # using variables as a parameter

Question:

When executing this request in C #, an error is thrown about the absence of one or more parameters, here sl, sp are program variables.

myOleDbCommand.CommandText = "SELECT Login FROM People WHERE Login=sl AND password=sp";

I tried like this, but it gives an error if one or more parameters are missing

myOleDbCommand.CommandText = "SELECT Login FROM People WHERE Login="+sl+" AND password="+sp;

Answer:

Use the parameters:

myOleDbCommand.CommandText = "SELECT Login FROM People WHERE Login=? AND password=?";
// параметры подставляются по порядку, именя можно задать любые
myOleDbCommand.Parameters.AddWithValue("Login", sl);
myOleDbCommand.Parameters.AddWithValue("Password", sp);

or better – named parameters:

myOleDbCommand.CommandText = "SELECT Login FROM People WHERE Login=@Login AND password=@Password";
// параметры подставляются по имени, старый Access такое может не переварить
myOleDbCommand.Parameters.AddWithValue("@Login", sl);
myOleDbCommand.Parameters.AddWithValue("@Password", sp);
Scroll to Top
AllEscort