[英]Winforms using SQL Server 2008
con = new SqlConnection(cs);
con.Open();
DateTime current = DateTime.Now;
current = Convert.ToDateTime(DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss"));
SqlCommand cmd = new SqlCommand(@"INSERT INTO CustomerDetails
(CustomerId, Date, Name, Gender, Address, Phone, Email, MobileNo,Notes)
VALUES ('" + txtCustomerID.Text + "','" + current + "','" +
txtCustomerName.Text + "','"+Gender+"','"+txtAddress.Text+"','" + txtPhone.Text
+ "','" + txtEmail.Text+"','" + txtMobileNo.Text + "','" +txtNotes.Text + "')",
con);
cmd.ExecuteNonQuery();
con.Close();
我在數據庫中使用此代碼,我的日期具有datetime
數據類型,但是當我通過表單保存數據時顯示錯誤:
varchar數據類型到datetime數據類型的轉換導致值超出范圍。
怎么了 為什么會顯示此錯誤?
您應該使用參數而不是連接字符串。 它不僅可以消除日期格式的問題,而且還可以防止SQL注入。
SqlCommand cmd = new SqlCommand(@"INSERT INTO CustomerDetails
(CustomerId, Date, Name, Gender, Address, Phone, Email, MobileNo,Notes)
VALUES (@CustomerId, @Date, @Email, @Mobile, @Notes)", con);
cmd.Parameters.Add("@CustomerId", SqlDbType.VarChar, 10).Value = txtCustomerID.Text;
cmd.Parameters.AddWithValue("@Date", SqlDbType.DateTime).Value = DateTime.Now;
cmd.Parameters.Add("@Email", SqlDbType.VarChar, 10).Value = txtEmail.Text;
cmd.Parameters.Add("@Mobile", SqlDbType.VarChar, 10).Value = txtMobileNo.Text;
cmd.Parameters.Add("@Notes", SqlDbType.VarChar, 10).Value = txtNotes.Text;
如果要存儲當前日期,請使用sql的getdate()
或SYSDATETIME()
函數。
嘗試這個:
SqlCommand cmd = new SqlCommand(@"INSERT INTO CustomerDetails
(CustomerId, Date, Name, Gender, Address, Phone, Email, MobileNo,Notes)
VALUES ('" + txtCustomerID.Text + "',+ getdate() + ,'" +
txtCustomerName.Text + "','"+Gender+"','"+txtAddress.Text+"','" + txtPhone.Text
+ "','" + txtEmail.Text+"','" + txtMobileNo.Text + "','" +txtNotes.Text + "')",
con);
建議:您的查詢對sql注入攻擊開放,所以我建議您使用Paramterised Queries以避免它們。
連接sql字符串時,您需要附加日期字符串,而不是datetime變量。 因此,除非您有其他原因將當前變量設置為日期,否則將其設置為字符串。
string current = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.