从C#winforms在sql数据库中只保存日期而不保存时间
我在将时间保存到SQL数据库时遇到了问题 当用户扫描大楼时,系统应将时间和日期保存到数据库中。在当前时刻,它保存日期,但时间保存为00:00 在保存过程中,我无法将日期转换为SQL,因此可能是在这个过程中出错了。我看了很久,不明白为什么它不能节省时间 有什么想法吗?这是有问题的代码从C#winforms在sql数据库中只保存日期而不保存时间,c#,sql,winforms,C#,Sql,Winforms,我在将时间保存到SQL数据库时遇到了问题 当用户扫描大楼时,系统应将时间和日期保存到数据库中。在当前时刻,它保存日期,但时间保存为00:00 在保存过程中,我无法将日期转换为SQL,因此可能是在这个过程中出错了。我看了很久,不明白为什么它不能节省时间 有什么想法吗?这是有问题的代码 var currentdate = DateTime.Now; var TimeAccess = currentdate.Date.ToString("yyyy-MM-dd
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";
谢谢也许是
DateTime
而不是第二行的Date
:
var TimeAccess = currentdate.DateTime.ToString("yyyy-MM-dd HH:mm:ss");
可能是
DateTime
而不是第二行中的Date
:
var TimeAccess = currentdate.DateTime.ToString("yyyy-MM-dd HH:mm:ss");
您不应该更改其数据类型并将其转换为
string
,如果数据库中有类型为date
或datetime
的列,只需将其直接传递到数据库:
com.Parameters.Add("@TimeAccess", SqlDbType.DateTime).Value = currentDate;
您不应该更改其数据类型并将其转换为
string
,如果数据库中有类型为date
或datetime
的列,只需将其直接传递到数据库:
com.Parameters.Add("@TimeAccess", SqlDbType.DateTime).Value = currentDate;
您可以直接传递
DateTime.Now
命令参数,并确保数据库列为DateTime
。就这样
com.Parameters.Add("@TimeAccess", SqlDbType.DateTime).Value = DateTime.Now;
您可以从代码中删除以下内容,因为它根本不是必需的
var currentdate = DateTime.Now;
var TimeAccess = currentdate.Date.ToString("yyyy-MM-dd HH:mm:ss");
您可以直接传递
DateTime.Now
命令参数,并确保数据库列为DateTime
。就这样
com.Parameters.Add("@TimeAccess", SqlDbType.DateTime).Value = DateTime.Now;
您可以从代码中删除以下内容,因为它根本不是必需的
var currentdate = DateTime.Now;
var TimeAccess = currentdate.Date.ToString("yyyy-MM-dd HH:mm:ss");
使用Getdate()
使用Getdate()你不能在SQL中使用Getdate函数而不是从代码中发送它吗?你不能在SQL中使用Getdate函数而不是从代码中发送它吗?这实际上是一个错误,但是whoöle到字符串的转换应该消失这实际上是一个错误,但是whoöle到字符串的转换应该消失谢谢你!我在这之前尝试过一些东西,但是我用了DateTime2而不是DateTime,再次感谢你,谢谢你!我在这之前尝试过一些东西,但是我用了DateTime2而不是DateTime,再次感谢