我正在创建一个新的应用程序,并试图将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();
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();
if (con.State == System.Data.ConnectionState.Open)
被表白的楼房 · 张羽(原中央电视台主持人)_百度百科 7 月前 |