Doubt with sql command in c#

Asked

Viewed 37 times

3

SqlCommand comm =
new SqlCommand("UPDATE Contatos Set Telefone=" + " ' " + txtTelefone.Text + " ' " + ",Cidade=" + " ' " + txtCidade.Text + " ' " + ",Email=" + " ' " + txtEmail.Text + " ' " + ",Endereco=" + " ' " + txtEndereco.Text + " ' " + "WHERE Nome=" + txtNome.Text, conn);

Error: "Column name 'the name that is in the invalid txtNome". The error message shows as if I was trying to find the name of a column, where the column name is txtNome.Text. My intention was for the sql command to update the contact information according to its name. I have little experience with sql and can’t see where my error is.

2 answers

6


This is the bad way to fire an SQL command. It is correct to create parameters for each field that will be updated:

SqlCommand comm = new SqlCommand("UPDATE Contatos Set Telefone = @Telefone, " +
                                 "Cidade = @Cidade, " +
                                 "Email = @Email, " +
                                 "Endereco = @Endereco " +
                                 "WHERE Nome = @Nome", conn);

comm.Parameters.AddWithValue("@Telefone", txtTelefone.Text);
comm.Parameters.AddWithValue("@Cidade", txtCidade.Text);
comm.Parameters.AddWithValue("@Email", txtEmail.Text);
comm.Parameters.AddWithValue("@Endereco", txtEndereco.Text);
comm.Parameters.AddWithValue("@Nome", txtNome.Text);
  • True, I’ll test it like this. It’s even better to understand.

3

In the clause Where failed to concatenate with simple quotes. Follows example below.

But you’d better take the advice that Gypsy Morrison Mendez gave.

"WHERE Nome=" + "'" + txtNome.Text + "'", conn);
  • The problem with this approach is the risk of SQL Injection.

  • How this SQL Injection happens?

  • Bruno Brito read this link, it is easy to understand about SQL Injection. https://pt.wikipedia.org/wiki/Inje%C3%A7%C3%A3o_de_sql

Browser other questions tagged

You are not signed in. Login or sign up in order to post.