Doubt with sql command in C #

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 'is the name that is in the' Invalid 'txtName. The error message shows as if I had been trying to fetch the name of a column, where the column name is txtName.Text. My intention was for the sql command to update the contact information according to its name. I have little experience with sql and I can not see where my error is.

    
asked by anonymous 26.11.2015 / 17:29

2 answers

6

This is the bad way to fire an SQL command. The correct thing is 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);
    
26.11.2015 / 17:34
3

In the where clause, you have to concatenate with single quotation marks. Here's an example below.

But you'd better follow the advice that Gypsy Morrison Mendez has passed.

"WHERE Nome=" + "'" + txtNome.Text + "'", conn);
    
26.11.2015 / 17:41