删除sql中的行?

时间:2015-08-22 13:32:03

标签: c# sql sql-delete

在这个AddPatient.cs中,我无法删除整行,但是当在C#中通过删除按钮操作执行此操作时,它无法正常工作,因此我需要帮助。

    private void Delete_Click(object sender, EventArgs e)
    {

       if (pno.Text != "" || pname.Text != "" || age.Text != "" || sex.Text != "" || add.Text != "" || city.Text != "" || phone.Text != "" || edate.Text != ""
            || dname.Text != "" || dig.Text != "" || dpname.Text != "")
            try
            {
                cn.Open();
                cmd.CommandText = 
                "delete from PatientDetails where PatientNumber= '" + pno.Text + "' and PatientName='" + pname.Text + "' and Age='" + age.Text + "' and Sex ='" + sex.Text + "' and PatientAddress='" + add.Text + "' and City='" + city.Text + "' and PhoneNumber='" + phone.Text + "' and EntryDate='" + edate.Text + "' and DoctorName='" + dname.Text + "' and Diagnosis='" + dig.Text + "' and  DepartmentName='" + dpname.Text + "'";
                cmd.ExecuteNonQuery();
                cmd.Clone();
                cn.Close();
                MessageBox.Show("Record Deleted Successfully");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

             }


    }

2 个答案:

答案 0 :(得分:4)

where子句中的分隔符为andor,而不是,

           "delete from PatientDetails where PatientNumber= '" + pno.Text + "' and PatientName='" + pname.Text + "' and Age='" + age.Text + "' and Sex ='" + sex.Text + "' and PatientAddress='" + add.Text + "' and City='" + city.Text + "' and PhoneNumber='" + phone.Text + "' and EntryDate='" + edate.Text + "' and DoctorName='" + dname.Text + "' and Diagnosis='" + dig.Text + "' and  DepartmentName='" + dpname.Text + "'";

但是,你应该真正删除id而不是列的长列表。

另外,请考虑使用参数化查询。将用户输入直接包含在字符串中不仅会引起SQL注入危险,而且会破坏系统。例如,如果其中一个名称是“O'Conner”。

答案 1 :(得分:0)

曾经听说过主键吗?曾经听说过Entity框架还是nhibernate?

不要那样手动的东西!