在Visual Studio中使用Windows窗体的日期格式
问题描述:
我试图用下面的查询来更新数据库,但是我很难格式化日期。我该怎么办?在Visual Studio中使用Windows窗体的日期格式
string query = "update employee_info set FirstName ='txtfirstName.Text',LastName ='txtlastName.Text' ,Address1='txt_address', City = 'combo_city' ,Country='combo_Country',ReportsTo='txt_reportTo' WHERE Bday='dtp_birthDate.Value.ToShortDateString()' and HireDate='dtp_hireDate.Value.ToShortDateString()'";
答
您应该改用参数化查询。这让你周围有格式化字符串正确的where子句,也阻止您容易受到SQL注入式攻击(https://en.wikipedia.org/wiki/SQL_injection)
像这样的东西(下面的样品具有查询的缩短版,缺乏建立一个数据库连接)。
strQuery = "update employee_info set [email protected], [email protected] WHERE [email protected] and [email protected]";
cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("@firstName", txtfirstName.Text);
cmd.Parameters.AddWithValue("@CompanyName", txtLastName.Text);
cmd.Parameters.AddWithValue("@birthDate", dtp_birthDate.Value);
cmd.Parameters.AddWithValue("@hireDate", dtp_hireDate.Value);
cmd.ExecuteNonQuery();
[SQL注入警报(http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - 你应该**永远**串连在一起你的SQL语句 - ***总是***使用**参数化查询**,而不是SQL注入 - 检查[小Bobby表](https://xkcd.com/327/) –
请不要发布问题仅限于问题标题 – Felix