Convert a DateTime Object in a SQL field
Tags:
This post is part of the SQLStringBuilder project. For the latest version of the code i suggest to take the source code from the CVS.
If we want to insert a date in a SQL string in C#, the solution seems obvious:
DateTime date = DateTime.Now; string sql = "INSERT INTO tableWithDate VALUES(1, "+ date.ToString() + ")";
Unfortunately this code can’t work! The function DateTime.ToString() returns a string like 23/02/2007 19.00.49, while MySQL wants a string like 2007-02-23 19:00:49. The following static function converts a DateTime object in a valid date field for MySQL:
public static string GetSQLDate(DateTime date)
{
string sql;
sql = date.Year.ToString() + "-" + date.Month.ToString() + "-" + date.Day.ToString() + " "
+ date.Hour.ToString() + ":" + date.Minute.ToString() + ":" + date.Second.ToString();
return sql;
}
I inserted the method in a utility class, that i called Utils, so the working code is:
string sql = "INSERT INTO tableWithDate VALUES(1, "+ Utils.GetSQLDate(date) + ")";
Se sei interessato a questo post, potresti anche provare a leggere:
- No related posts
15 Jun 2007 dzamir
Personally I think it would be much easier to use a parameterized query and let the provider handle the interpretation of the dateTime. This has a number of benefits
1) Pretty much database agnostic
2) Shields you from nasty things like regional settings. You realize your code would fail if my database is configured for English UK (d-mm-yyyy)
One word: Localization
Seriously, this is a shoddy solution to a meager problem.