Error trying to update table using C #

7

I created a form to change a table, but my update is not working.

    cnxCli.sel =/*"set dateformat dmy \n"+ */
                "update Cliente" +
                 "set Nome = '" + txtNome.Text +"'," +
                 "Rg = '" + mskRg.Text + "'," +
                 "Cpf ='" + mskCpf.Text + "'," +
                 "Celular ='" + mskCelular + "'," +
                 "Telefone ='" + mskTelefone + "'," +
                 "DataNascimento = '" + mskNascimento.Text + "'," +
                 "Endereco ='" + txtEndereco.Text + "'," +
                 "Bairro='" + txtBairro.Text + "'," +
                 "Cidade='" + "'," +
                 "Cep ='" + mskCep.Text + "'," +
                 "Observacao='" + txtObs.Text + "'" +
                 "where IDCliente =" + IdCliSel;
    cnxCli.selCmd.CommandText = cnxCli.sel;
    bool deuErro = false;
    try
    {
        cnxCli.selCmd.ExecuteNonQuery();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
        deuErro = true;
        //throw;
    }
    if (!deuErro)
        MessageBox.Show("Cadastro do cliente " + IdCliSel + " atualizado com sucesso!");

The exception thrown: System.Data.SqlClient.SqlException - Incorrect syntax near 'Nome' .

For me the syntax seems correct, so much so that I copied the code straight from SQL Server 2014, where I had just run the command.

    
asked by anonymous 16.12.2015 / 02:32

2 answers

6

There is a syntax error because a space in "update Cliente" + is missing, so you have put everything together.

But this is a minor problem. The whole code has several problems.

Never mount a query this way it is insecure and disorganized. See documentation the way correct to do.

There may still be a memory leak.

Even though doing this wrong, it could still be simplified, and simpler things give less errors and when they happen, they are easier to find.

The exception capture form is wrong. I teach in various answers .

Are all columns varchar ? It's unlikely. It will give other errors correcting this.

It has other little problems and something indicates that the rest of the code is bad as well. So it accumulates problems and it is tiring and thinking that the problem is in the programming language. You have to learn how it does, it has to be something structured, it is no use following cake recipes.

    
16.12.2015 / 02:44
2

A space must be given between the Cliente table and the set command:

cnxCli.sel =/*"set dateformat dmy \n"+ */
                "update Cliente" +
                 "set Nome = '"

Switch to:

cnxCli.sel =/*"set dateformat dmy \n"+ */
                "update Cliente " + /*<-----Mudei aqui.*/
                 "set Nome = '"
    
16.12.2015 / 02:38