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