[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 500
  • Last Modified:

DateTime With C# and MS SQL

Hello,

I seem to be missing something from this code, it always generates an incorrect syntax error.. how do I cast a C# DateTime to a MSSQL DateTime?

Thanks for you time
DateTime dateTime = new DateTime(2006, 09, 07, 22, 21, 44);
SqlCommand myCommand = new SqlCommand("SELECT * FROM Mytable1 WHERE MyDateAndTime = " + dateTime, myConnection);

 mySqlDataReader = myCommand.ExecuteReader();

Open in new window

0
setfocus
Asked:
setfocus
  • 2
1 Solution
 
käµfm³d 👽Commented:
Best practice:   Like this...
DateTime dateTime = new DateTime(2006, 09, 07, 22, 21, 44);

SqlCommand myCommand = new SqlCommand("SELECT * FROM Mytable1 WHERE MyDateAndTime = @myDate", myConnection);

myCommand.Parameters.Add(new SqlParameter("@myDate", dateTime));

mySqlDataReader = myCommand.ExecuteReader();

Open in new window

0
 
RiteshShahCommented:
I too agree with above suggestions, why do you want to invite hackers and SQL Injection? use parameter saw above.....
0
 
setfocusAuthor Commented:
That's Excellent! Thanks very much for your time...
0
 
käµfm³d 👽Commented:
NP. Glad to help  :)
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now