爱运动的手电筒 · 幽冥诡匠 - 抖音百科· 4 月前 · |
玩滑板的牛肉面 · 如何评价柳永? - 知乎· 7 月前 · |
多情的圣诞树 · 【误解向】《The Boy/灵偶契约 ...· 1 年前 · |
打篮球的红酒 · 东莞制造年中观察|氢燃料电池产业链雏形显现, ...· 1 年前 · |
无邪的圣诞树 · 风向变了!国产车开始反向输出了?|丰田|赛弗 ...· 1 年前 · |
我正在创建一个新的应用程序,并试图将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)