如何在C#中向MySql数据库添加日期(DateTime.now) [英] how to add a date (DateTime.now) to a mySql database in C#
问题描述
我一直在研究如何使用Visual Studio将日期插入到mySql数据库中.我了解了mySql仅接受某种格式的错误,并且我已经在stackoverflow上浏览了有关此内容的网络和其他类似主题...但是几乎所有示例都将日期作为预制字符串,使用parseexact转换
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
它看起来像这样:
result = DateTime.ParseExact(nowstring, format, provider)
但是事情是我正在尝试使用dateTime.now函数.每当程序执行某项操作时,我都希望将实时dateTime添加到数据库中.根据我的研究,它应该看起来像这样.
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.
只需将您的 DateTime.Now
直接传递到表的参数化插入查询中即可.
Just pass your DateTime.Now
directly to your parameterized insert query to your table.
MySQL不会将您的 DateTime
值另存为这些列类型的字符.它将它们保留为人类无法阅读的二进制文件.您可以在数据库中以'YYYY-MM-DD'
或'YYYY-MM-DD HH:MM:SS'
格式查看它们.
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.
例如;
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();
}
这篇关于如何在C#中向MySql数据库添加日期(DateTime.now)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!