0

I am building a Point of Sales system in C# and I am passing the data from the Interface through an object to the database.

The update function throws a Syntax Error in cmd.CommandText every time I try to update.

private void btnUpdate_Click(object sender, EventArgs e) //UPDATE FUNCTION//
    {
            user_management_system user_mgnt = new user_management_system();
            user_mgnt.Username = txt_userName.Text;
            user_mgnt.Password = txt_password.Text;
            user_mgnt.First_name = txt_firstName.Text;
            user_mgnt.Last_name = txt_lastName.Text;
            user_mgnt.Nationality = txt_nationality.Text;
            user_mgnt.Email = txt_email.Text;
            user_mgnt.Age = (txt_age.Text);
            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "UPDATE userlogin SET password = ('"+ user_mgnt.Password + "',first_name='" + user_mgnt.First_name + "',last_name='" + user_mgnt.Last_name + "',age='" + user_mgnt.Age +
                          "',nationality='" + user_mgnt.Nationality + "',email='" + user_mgnt.Email + "', WHERE username ='"+ user_mgnt.Username+ "')";
           cmd.ExecuteNonQuery();
            con.Close();
            MessageBox.Show("Data has been successfuly updated");
            displaydata();
2
  • 5
    If you don't use parameters, you are going to have a bad time. SQL Injection, formatting errors, etc. Commented Jul 21, 2017 at 21:06
  • 6
    The very first thing to do is stop building SQL like that. Use parameterized SQL, always. Aside from anything else, it will make it a lot easier to see the SQL you're actually using. (Then there's removing SQL injection attacks.) Next, it looks like you're storing passwords in plain text - I'd very strongly recommend that you stop doing that, too. Commented Jul 21, 2017 at 21:07

2 Answers 2

2

You have an extra (misplaced) comma before your WHERE clause. It should be:

cmd.CommandText = "UPDATE userlogin SET password = ('"+ user_mgnt.Password + "',first_name='" + user_mgnt.First_name + "',last_name='" + user_mgnt.Last_name + "',age='" + user_mgnt.Age +
                          "',nationality='" + user_mgnt.Nationality + "',email='" + user_mgnt.Email + "' WHERE username ='"+ user_mgnt.Username+ "')";

EDIT: And I would agree with those commenting that you should use parameterized SQL, and also avoid storing plain text passwords in the DB.

Sign up to request clarification or add additional context in comments.

Comments

-1

There is a syntax error in the query text please follow this form

https://www.w3schools.com/sql/sql_update.asp

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.