0

我正在 C#.NET 和 SQL Server 2012 中开发数据库应用程序。我的一些 SQL 语句无法正常工作。当我执行代码时,它不会给出任何错误。但是当我尝试删除某些内容或更新记录时,我不会那样做。代码如下:

    public void updateFinalTable()
    {
        DialogResult result = MessageBox.Show("Please make sure no fields are empty or they will get changed. \n\t\t Do you want to continue?",
        "Important Note",
        MessageBoxButtons.YesNo);
        if (result == DialogResult.Yes)
        {
            try
            {
                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);

                con.Open();
                SqlCommand cmd = new SqlCommand("UPDATE fianlTable SET   AccountNumber='" + textBox1.Text + "', Date='" + dateTimePicker1.Value.ToString("MM/dd/yyyy") + "', CustomerName='" + textBox3.Text + "' , Debit='" + txtDebit.Text + "', Credit='" + txtCredit.Text + "', Balance='" + txtBalance.Text + "'  WHERE Id LIKE '" + textBox4.Text + "' ", con);
                cmd.ExecuteNonQuery();
                this.fianlTableBindingSource.AddNew();
                DataTable dt = new DataTable();
                SqlDataAdapter sda = new SqlDataAdapter("select * from fianlTable WHERE (UserName LIKE '" + LoginSession.UserID + "')", con);

                sda.Fill(dt);
                dataGridView1.DataSource = dt;
                refresh();
                con.Close();

                MessageBox.Show("Record Updated Successfully!");

            catch (Exception)
            {
                MessageBox.Show("Record Could Not be updated...!   ");
            }
        }
    }

删除操作也是如此。两个代码都没有错误,但在数据库内部没有观察到任何变化。

4

1 回答 1

1

Like在 where 条件中使用了而不是=. 所以你的代码应该是这样的 -

SqlCommand cmd = new SqlCommand("UPDATE fianlTable SET AccountNumber='" + textBox1.Text + "', Date='" + 
dateTimePicker1.Value.ToString("MM/dd/yyyy") + "', CustomerName='" +
textBox3.Text + "' , Debit='" + txtDebit.Text + "', Credit='" + 
txtCredit.Text + "', Balance='" + txtBalance.Text + 
"'  WHERE Id = '" + textBox4.Text + "' ", con);

注意这种类型的查询可能会导致 SQL 注入。你最好使用参数化查询,像这样 -

string qry = = "UPDATE fianlTable SET AccountNumber = @accnt, CustomerName = @cname Where ID = @id)";

 SqlCommand cmd = new SqlCommand(qry, con);
 cmd.Parameters.AddWithValue("@accnt", textBox1.Text);
 cmd.Parameters.AddWithValue("@cname", textBox3.Text);
 cmd.Parameters.AddWithValue("@id", textBox4.Text);  
 cmd.ExecuteNonQuery();
于 2016-05-17T20:43:52.887 回答