MySQL and MySQL Community information

  • January 3, 2012

Milliseconds value support on DateTime Columns

Since the release of the 5.6 Community MySQL Server there is support for the milliseconds value in Time, TimeStamp and DateTime types.  You can find more information on this new feature at (http://dev.mysql.com/doc/refman/5.6/en/fractional-seconds.html).  Starting with version 6.5, Connector/Net fully supports milliseconds. This support does not affect compatibility with older versions of MySQL and it gives you the ability to use fractional seconds when combining Connector/Net 6.5 with MySQL Server 5.6 or later.  Let's see how we should use it.

Creating a DateTime column that include Milliseconds value.

You can do this either using Connector/Net or using any MySQL client with a valid connection to your database.

For this case we're going to use MySqlCommand class within a console application in VS 2010.

1. Define the connection string to use and create the table in our database: 

MySqlConnection conn = new MySqlConnection("host=localhost;User Id=root;pooling=False;Persist Security Info=True;Connection Reset=True;Allow User Variables=True;database=test;"); 

MySqlCommand cmd = new MySqlCommand();

cmd.Connection = conn;

cmd.CommandText = "CREATE TABLE Test (id INT NOT NULL, dt DATETIME(6), PRIMARY KEY(id))";


2. Now let's use a MySqlParameter to insert one row that has our field dt with milliseconds value:

cmd.CommandText = "INSERT INTO Test VALUES(@id, @dt)";

cmd.Parameters.Add(new MySqlParameter("@id", 1));

MySqlParameter dt  = new MySqlParameter();

dt.ParameterName = "@dt";

dt.MySqlDbType = MySqlDbType.DateTime;

dt.Value = "2011-01-01 12:34:59.123456";



3.  Query your table to see that this value was in fact saved including the milliseconds value:

cmd.CommandText = "SELECT dt FROM Test WHERE id = 1";


cmd.Connection = c;


MySqlDataReader rdr = cmd.ExecuteReader();

while (rdr.Read()){

Console.WriteLine(rdr[0] + " --- " + rdr.GetMySqlDateTime(1).Millisecond + " -- ");




The output for this code should be:

 1 --- 123456 --

Notice that I used the GetMySqlDateTime method to read the complete value of the milliseconds. If you use GetDateTime method instead you will have only the first three digits since this is a limitation on the milliseconds value for the DateTime class on the .Net framework. You can also use this feature using prepared statements.

Please feel free to ask any questions and post any comments you have.  We would like to hear you!

Happy MySql/Net Codding!! 

Be the first to comment

Comments ( 0 )
Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.Captcha

Integrated Cloud Applications & Platform Services