简体   繁体   中英

how to add a date (DateTime.now) to a mySql database in C#

I have been researching on how to insert a date into my mySql database using the visual studio. I understand the error that mySql only accepts a certain format and I've been browsing both the net and other similar topics about this here on stackoverflow... but almost all the examples have the date as a pre-made string that is changed using the parseexact conversion

It looks something like this:

result = DateTime.ParseExact(nowstring, format, provider)

But the thing is I'm trying this with a dateTime.now function. I want a realtime dateTime added to the database each time my program does something.. well from what I researched, it should look something like this..

string nowstring, format;
                DateTime result;
                System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
                format = "yyyy-MM-dd";
                nowstring = DateTime.Now.ToString();
                result = DateTime.ParseExact(nowstring, format, provider);

I guess I'm just doing something wrong since we havent tackled this at school yet or im just simply missing something elementary. Either way, I'd glady appreciate your help.

If your column that you want to insert DATE or DATETIME type , you don't need any of these formatting and parsing operations.

Just pass your DateTime.Now directly to your parameterized insert query to your table.

MySQL doesn't save your DateTime values as a character for these column types. It keeps them as a binary which humans can't read. You can see them with 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS' format as a representation in your database.

For example;

using(var con = new MySqlConnection(conString))
using(var cmd = con.CreateCommand())
{
   cmd.CommandText = "insert into tbl_operators (DateJoined) values (@date)";
   cmd.Parameters.AddWithValue("@date", DateTime.Now);
   con.Open();
   cmd.ExecuteNonQuery();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM