user3499965
user3499965

Reputation: 5

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.

Upvotes: 0

Views: 527

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500365

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.

Upvotes: 3

Damith
Damith

Reputation: 63065

you better to use parameter for date like below

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

create date time from your cmdb_Date2, for example if the date time format is "yyyy-MM-dd HH:mm" then

DateTime dt = 
    DateTime.ParseExact(cmdb_Date2.Text, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);

now you can set the parameter value like below

cmd.Parameters.Add("Date_Ajout ", OleDbType.Date).Value = dt;

execute the cmd

Upvotes: 0

Related Questions