views:

137

answers:

2

How do I format the string result of DateTime.Now in C# for insertion into a MySQL database table column of type DATETIME?

I have tried the following without any success:

insert blah 
  (Id, Content, DateCreated) 
  select 123, 'Blah blah blah', 1/5/2010 9:04:58 PM

insert blah 
  (Id, Content, DateCreated) 
  select 123, 'Blah blah blah', '1/5/2010 9:04:58 PM'
+5  A: 

Don't put literal dates in the query, use parameters instead. That way you don't have to worry about the format. It is also safer for strings entered by users, because it prevents SQL injections.

command.Text = "insert into myTable(myDate) values(?dateParam)";
command.Parameters.Add("?dateParam", theDate);
Thomas Levesque
Excellent, thanks!
jamesaharvey
Always use parameters like this: for _all_ your data types, not just date times.
Joel Coehoorn
+1  A: 

Use a parameterized MySqlCommand rather than building your own query and pass a DateTime to as the parameter. No formatting necessary.

Randolpho