[英]Only Date is saved and not time in sql Database from C# winforms
I'm having an issue with saving the time into my SQL database. 我在将时间节省到SQL数据库时遇到问题。
The system should save time and date to the database when the user scans into the building. 当用户扫描建筑物时,系统应将时间和日期保存到数据库中。 At the current moment it saves date but time is saved as 00:00.
当前,它保存日期,但时间保存为00:00。
I had problems converting the date to SQL during the save process, so maybe i've made a mistake in the process. 我在保存过程中将日期转换为SQL时遇到问题,所以也许我在过程中犯了一个错误。 I've looked at it for ages and cant see why it wouldnt save the time as well.
我已经看了很久了,看不到为什么它也不能节省时间。
Any ideas? 有任何想法吗? here is the code in question
这是有问题的代码
var currentdate = DateTime.Now;
var TimeAccess = currentdate.Date.ToString("yyyy-MM-dd HH:mm:ss");
SqlCommand com = new SqlCommand();
com.Connection = new SqlConnection(Properties.Settings.Default.BioEngineering);
com.Connection.Open();
com.CommandText = "INSERT INTO AccessHistory (DoorID,UserID,TimeAccess,Status) VALUES (@DoorID,@UserID,@TimeAccess,@Status)";
com.Parameters.Add("@DoorID", SqlDbType.Int).Value = DoorNumber;
com.Parameters.Add("@UserID", SqlDbType.Int).Value = cboUserID.Text;
com.Parameters.Add("@TimeAccess", SqlDbType.DateTime).Value = TimeAccess;
com.Parameters.Add("@Status", SqlDbType.VarChar).Value = "Successful";
Thank you 谢谢
如果您的数据库中有date
或datetime
类型的列,则不应更改其数据类型并将其转换为string
,而应将其直接传递给数据库:
com.Parameters.Add("@TimeAccess", SqlDbType.DateTime).Value = currentDate;
也许用DateTime
代替第二行中的Date
:
var TimeAccess = currentdate.DateTime.ToString("yyyy-MM-dd HH:mm:ss");
You can directly pass DateTime.Now
for command parameters and make sure database column is DateTime
. 您可以直接传递
DateTime.Now
作为命令参数,并确保数据库DateTime
。 That's It. 而已。
com.Parameters.Add("@TimeAccess", SqlDbType.DateTime).Value = DateTime.Now;
You can remove below from your code as It is not required at all. 您可以从代码中删除以下内容,因为完全不需要。
var currentdate = DateTime.Now;
var TimeAccess = currentdate.Date.ToString("yyyy-MM-dd HH:mm:ss");
SqlCommand com = new SqlCommand();
com.Connection = new SqlConnection(Properties.Settings.Default.BioEngineering);
com.Connection.Open();
com.CommandText = "INSERT INTO AccessHistory (DoorID,UserID,TimeAccess,Status) VALUES (@DoorID,@UserID,getdate(),@Status)";
com.Parameters.Add("@DoorID", SqlDbType.Int).Value = DoorNumber;
com.Parameters.Add("@UserID", SqlDbType.Int).Value = cboUserID.Text;
com.Parameters.Add("@Status", SqlDbType.VarChar).Value = "Successful";
Use Getdate() 使用Getdate()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.