Getting data value using date condition

I get Syntax error (missing operator) in query expression

string strSql2 = "Select N_Serie,MacID from " + cmdb_ModelStock2.Text + " WHERE Date_Ajout = " + cmdb_Date2.Text;

I put a break a point and debugg step by step, and I see, it get the date and also the time. could that be the problem?? If so is it possible to make it get only the date not the time.

Jon Skeet
people
quotationmark

The first thing to do is to stop constructing your SQL like that. If you really need to pick the table dynamically, you should make sure you use a whitelist of valid ones... but for the "where" clause you should use parameterized SQL - parse cmdb_Date2.Text into a DateTime, and specify that as the parameter value. Using parameterized SQL protects you from SQL injection attacks, avoids conversion issues, and makes it easier to read your SQL.

So:

string tableName = ValidateTableName(cmdb_ModelStock2.Text); // TODO: Write this!
DateTime date = DateTime.Parse(cmdb_Date2.Text); // See below
string sql = "Select N_Serie,MacID from " + tableName + " WHERE Date_Ajout = ?";
using (var command = new OleDbCommand(sql, conn))
{
    // Or use type "Date", perhaps... but that would be more appropriate
    // with a range. The name doesn't matter using OLE, which uses positional
    // parameters.
    command.Parameters.Add("Date", OleDbType.DBDate).Value = date;
    // Execute the command etc
}

Note that here I'm using DateTime.Parse, but ideally you'd use a UI control which gives a DateTime directly. (We don't know what kind of UI you're using, which makes it hard to give advice here.)

Depending on what data type you're using in the database, you might want to use a BETWEEN query instead of an exact match.

people

See more on this question at Stackoverflow