[英]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. 我一直在研究如何使用Visual Studio将日期插入到mySql数据库中。 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
我了解了mySql仅接受某种格式的错误,并且我一直在Stackoverflow上浏览有关此内容的网络和其他类似主题...但是,几乎所有示例都将日期作为预制字符串,使用parseexact转换
It looks something like this: 看起来像这样:
result = DateTime.ParseExact(nowstring, format, provider)
But the thing is I'm trying this with a dateTime.now function. 但问题是我正在尝试使用dateTime.now函数。 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..
我希望每次程序执行某项操作时,都将实时dateTime添加到数据库中。根据我的研究,它应该看起来像这样。
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. 如果您要插入
DATE
或DATETIME
类型的列 ,则不需要任何这些格式化和解析操作。
Just pass your DateTime.Now
directly to your parameterized insert query to your table. 只需将
DateTime.Now
直接传递到表的参数化插入查询即可。
MySQL doesn't save your DateTime
values as a character for these column types. MySQL不会将您的
DateTime
值另存为这些列类型的字符。 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. 您可以在数据库中以
'YYYY-MM-DD'
或'YYYY-MM-DD HH:MM:SS'
格式查看它们。
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.