簡體   English   中英

錯誤:從字符串轉換日期和/或時間時轉換失敗

[英]Error : Conversion failed when converting date and/or time from character string

在SQL表中Date_Of_BirthDate_Of_Joining數據類型是date 我需要執行update

我有這個代碼,它顯示錯誤 - Conversion failed when converting date and/or time from character string. 請幫忙。

string sql = "UPDATE Employees SET Designation = '" +textBox_BEUpdtD.Text + 
    "', Employee_Subgroup = '" +comboBox_BEupdt.Text + 
    "', Date_Of_Birth = " + dateTimePicker_DOBUpdt.Text + 
    ", Date_Of_Joining = " + dateTimePicker_DojUpdt.Text + 
    " Where Employee_Name ='"+comboBox_EmpNm.Text+"' ";

SqlCommand cmd7 = new SqlCommand(, con7);
con7.Open();
int o = cmd7.ExecuteNonQuery();
MessageBox.Show(o +" : Record has been updated"); '

除了將用戶變量直接發送到數據庫的SQL注入問題之外,我建議使用參數化查詢來簡化您嘗試執行的操作。

SqlCommand cmd7 = new SqlCommand("UPDATE Employees SET Designation = @designation, Employee_Subgroup = @subgroup, Date_Of_Birth = @dateofbirth, Date_Of_Joining = @dateofjoining Where Employee_Name = @employeename", con7);
cmd7.Parameters.AddWithValue("designation", textBox_BEUpdtD.Text);
cmd7.Parameters.AddWithValue("subgroup", comboBox_BEupdt.Text);
cmd7.Parameters.AddWithValue("dateofbirth", dateTimePicker_DOBUpdt.Value.Date);
cmd7.Parameters.AddWithValue("dateofjoining", dateTimePicker_DojUpdt.Value.Date);
cmd7.Parameters.AddWithValue("employeename",comboBox_EmpNm.Text);
con7.Open();
int o = cmd7.ExecuteNonQuery();
MessageBox.Show(o +" : Record has been updated")

也就是說,您的數據庫架構存在一些問題。 我強烈建議您不要關鍵員工姓名,因為:A)它不一定是唯一的,B)可能會以這種形式輸入錯誤,因為它只是一個純文本框,C)可能會隨着時間的推移而改變(例如婚姻等) )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM