SQL Query Command not working but does not give error SQL Server

2.2k views Asked by At

I am developing a database application in C#.NET and SQL Server 2012. Some of my SQL statements are not working properly . When I execute the code it does not give any error. But when I try to delete something or Update a record, I does not do that. The code lies below:

    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...!   ");
            }
        }
    }

Similar is the case with delete operation . Both codes give no error but inside the database no change is observed.

1

There are 1 answers

1
Krishnraj Rana On

You have used Like in your where condition instead of =. So your code should be like this -

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

ATTENTION This type of query potentially lead to SQL Injection. You better go with parametrized queries, like this -

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();