我正在创建一个新的应用程序,并试图将DateTime数据类型插入到SQLServer中。错误说
从字符串转换日期和/或时间时,转换失败。
代码:
string Insertcmd = "INSERT INTO PatientPay (PatientID, Cash, AmountPaid,
PaymentDate, Reseaon, StaffID) Values (@StaffID, @Cash, @AmountPaid,
@type, @PaymentDate, @StaffID)";
cmd = new SqlCommand(Insertcmd, con);
SqlParameter[] param = new SqlParameter[6];
param[0] = new SqlParameter("@PatientID", SqlDbType.Int);
param[0].Value = PatientID;
param[1] = new SqlParameter("@Cash", SqlDbType.Float);
param[1].Value = Cash;
param[2] = new SqlParameter("@AmountPaid", SqlDbType.Float);
param[2].Value = AmountPaid;
param[3] = new SqlParameter("@type", SqlDbType.NVarChar, 255);
param[3].Value = type;
param[4] = new SqlParameter("@PaymentDate", SqlDbType.DateTime);
param[4].Value = Convert.ToDateTime( DateTime.Now.ToString("yyyy-
MM-dd 00:00:00")); // Error
param[5] = new SqlParameter("@StaffID", SqlDbType.Int, 255);
param[5].Value = StaffID;
//Open the connection to database
con.Open();
try
{
if (con.State == System.Data.ConnectionState.Open)
{
//Execute the Adding process
cmd.Parameters.AddRange(param);
cmd.ExecuteNonQuery();
}
}catch{}
发布于 2019-05-01 23:14:20
只管用
param[4].Value = DateTime.Now;
而不是
param[4].Value = Convert.ToDateTime( DateTime.Now.ToString("yyyy-
MM-dd 00:00:00"));
如果需要删除时间部分,请使用:
param[4].Value = DateTime.Now.Date;
或者正如@DBro在评论中提到的那样
param[4].Value = DateTime.Today;
更新1
如果在传递日期参数时遇到问题,请使用以下sql命令,而不传递PaymentDate参数:
string Insertcmd = "INSERT INTO PatientPay (PatientID, Cash, AmountPaid,
PaymentDate, Reseaon, StaffID) Values (@StaffID, @Cash, @AmountPaid,
@type, DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0), @StaffID)";
整个守则将是:
string Insertcmd = "INSERT INTO PatientPay (PatientID, Cash, AmountPaid,
PaymentDate, Reseaon, StaffID) Values (@StaffID, @Cash, @AmountPaid,
@type, DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0), @StaffID)";
cmd = new SqlCommand(Insertcmd, con);
SqlParameter[] param = new SqlParameter[5];
param[0] = new SqlParameter("@PatientID", SqlDbType.Int);
param[0].Value = PatientID;
param[1] = new SqlParameter("@Cash", SqlDbType.Float);
param[1].Value = Cash;
param[2] = new SqlParameter("@AmountPaid", SqlDbType.Float);
param[2].Value = AmountPaid;
param[3] = new SqlParameter("@type", SqlDbType.NVarChar, 255);
param[3].Value = type;
param[4] = new SqlParameter("@StaffID", SqlDbType.Int, 255);
param[4].Value = StaffID;
//Open the connection to database
con.Open();
try
{
if (con.State == System.Data.ConnectionState.Open)
{
//Execute the Adding process
cmd.Parameters.AddRange(param);
cmd.ExecuteNonQuery();
}
}catch{}
参考
更新2
您必须重新排序SQL命令中的参数,因为您要在PaymentDate列中插入thr @type参数。
https://stackoverflow.com/questions/55943820
复制相似问题