如何以正确的方式在SQL Server数据库中添加日期

本文关键字:Server SQL 数据库 日期 添加 方式 | 更新日期: 2023-09-27 18:27:57

我花了两天时间试图在数据库表中添加日期,但每次我看到这个12:00:00 AM值而不是实际时间。对于这个简单的问题,我已经尽力了。

http://puu.sh/cpP2l/0b0dd66042.png

obj.Payment_date = DateTime.Now.ToString("G");
using (SqlCommand command = new SqlCommand("INSERT into Payments([software_id] ,[email] ,[ip] ,[payment_status] ,[payment_date] ,[transaction_id] ,[amount] ,[license_type] ,[license_status] ,[cd_key]) VALUES(@software_id ,@email ,@ip ,@payment_status ,@payment_date ,@transaction_id ,@amount ,@license_type ,@license_status ,@cd_key)", con))
{
    command.Parameters.Add(new SqlParameter("software_id", obj.Software_id)); 
    command.Parameters.Add(new SqlParameter("email", obj.Email));
    command.Parameters.Add(new SqlParameter("ip", obj.IP));
    command.Parameters.Add(new SqlParameter("payment_status",obj.Payment_status)); 
    command.Parameters.Add(new SqlParameter("payment_date", obj.Payment_date));
    command.Parameters.Add(new SqlParameter("transaction_id", obj.Transaction_id));
    command.Parameters.Add(new SqlParameter("amount", obj.Amount));
    command.Parameters.Add(new SqlParameter("license_type", obj.License_type));
    command.Parameters.Add(new SqlParameter("license_status",obj.License_status));
    command.Parameters.Add(new SqlParameter("cd_key", obj.Cd_key));
    if (command.ExecuteNonQuery() > 0)
    {
    }
}

如何以正确的方式在SQL Server数据库中添加日期

确保您已创建具有DateTime数据类型的Payment_date。

并设置Date&时间是这样的:

obj.Payment_date= DateTime.Now

如果您想要在插入时记录日期和时间,那么您最好为您的列添加一个默认约束:

ALTER TABLE Payments
ADD CONSTRAINT df_CurrentDateTime
DEFAULT CURRENT_TIMESTAMP FOR [Payment_Date]

在这种情况下,您根本不需要为Payment_Date字段提供参数。

编辑:如果上述解决方案不适合您的需求,那么我建议提供命令对象使用的Payment_Date参数的参数类型。

例如:尝试

SqlParameter myParam = new SqlParameter("payment_date", obj.Payment_date);   
myParam.DbType = System.Data.DbType.DateTime;
command.Parameters.Add(myParam);