1

In my program I'm saving date from DateTimePicker into the global variable with My.Settings.date = dtpDate_do.Value.Date. I'm using this date to compare date from my database but I'm always getting syntax error, no matter what I'm changing. This is my query:

cmd.CommandText = "SELECT ID, order_date FROM orders WHERE order_date = " & My.Settings.date & " ORDER BY ID DESC" 


Dates in my database are stored in EU format with dots - 17.2.2014. Can anyone provide me some help.

4
  • Post your syntax error as well. Commented Feb 17, 2014 at 6:25
  • Syntax error is likely because there are no quotes around the date. Commented Feb 17, 2014 at 6:28
  • what do you get in My.Settings.date ? As in the actual value at runtime when you debug? Commented Feb 17, 2014 at 6:29
  • dear friend check the post bellow Commented Feb 17, 2014 at 6:31

2 Answers 2

1

Never ever create your query like that. Always and without any exception use parameters. This avoids both SQL-injection attacts and ensures proper formatting of your parameters.

Sorry for not knowing VB.NET, but it should be similar to this:

cmd.CommandText = "SELECT ID, order_date FROM orders WHERE order_date = @Date ORDER BY ID DESC" 
cmd.Parameters.AddWithValue("@Date", My.Settings.data)

Explanation: Create your query using @ParamName as a placeholder for your parameters. Then substitute your parameters with values. Make sure to either apply a concrete typed value (i.e. not an object) or/and supply the data type otherwise.

Sign up to request clarification or add additional context in comments.

3 Comments

Ty alzaimar. Your approach worked as planned. But now I'm getting another error on program startup. COM object that has been separated from its underlying RCW cannot be used. Do u have any idea what why is that happening?.
I've tried with local variables but there is still this error. Maybe is it caused somewhere in code ahead. Dunno.
0

Try to use a parameter in the query like this:

cmd.CommandText = "SELECT ID, order_date FROM orders WHERE order_date = @date ORDER BY ID DESC";
cmd.Parameters.Add(new SqlParameter("@date", dateTimePicker.Value.Date));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.