1

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'
1
  • Not sure about MySQL, for SQL Server I use "yyyy-MM-dd HH:mm:ss" Commented Jan 6, 2010 at 2:11

2 Answers 2

5

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Always use parameters like this: for all your data types, not just date times.
1

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

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.