简体   繁体   中英

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

In SQL table Date_Of_Birth and Date_Of_Joining data type is date . I need to perform update .

I have this code and it's showing an error - Conversion failed when converting date and/or time from character string. Please help.

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"); '

Aside from the SQL Injection issues with sending in user variables directly to the database, I suggest using parameterized queries to simplify what you're trying to do.

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")

That said, there are some issues with your database schema. I strongly suggest that you do not key on employee name, as: A) It's not necessarily unique, B) May be mistyped in this form as it's just a pure text box, C) May change over time (eg. marriage, etc.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM