How to create the command line to update fields from the [closed]

-2

I have a job to insert, update and delete. The insert and delete are working correctly. So I have a problem in the update code that would be this:

 cmd.CommandText = "Update carros set placa='" + campoplaca.Text + "', marca='" + campomarca.Text + "' where placa='" + campoplaca.Text + "' and marca= '" + campomarca.Text + "'";

In my project I have values:

id=int pk
placa=nvarchar
marca=nvarchar
modelo=nvarchar
combustivel=nvarchar
potencia=int
ano=int
preco=int

Soon my question is how to proceed with this command line. Where there is already a tag and a tag, my wish for where is to change for the tag and then the other fields. More will be needed and at all?

private void btAtualizar_Click(object sender, EventArgs e)
        {
            SqlCeConnection conn;
            try
            {
                conn = new SqlCeConnection(" Data Source = C:\Users\Admin\Documents\Visual Studio 2015\Projects\WindowsFormsArrayEx03\BD_Teste.sdf; Password ='' ");
                conn.Open();
                MessageBox.Show("ATUALIZADO!!!");

            SqlCeCommand cmd = conn.CreateCommand();

            cmd.CommandText = "Update carros set placa='" + campoplaca.Text + "', marca='" + campomarca.Text + "' where placa='" + campoplaca.Text + "' and marca= '" + campomarca.Text + "'";

            cmd.ExecuteNonQuery();
            conn.Close();
        }
        catch (Exception ex)

        {
            MessageBox.Show(ex.StackTrace);

        }
    }
    
asked by anonymous 30.09.2016 / 15:50

1 answer

1

First, it is not advisable to concatenate sql statements as you did.

cmd.CommandText = "Update carros set placa='" + campoplaca.Text + "', marca='" + campomarca.Text + "' where placa='" + campoplaca.Text + "' and marca= '" + campomarca.Text + "'";

See a possibility for your example, make your where using the table's primary key. This way you can change both placa and marca in a same update statement.

cmd.CommandText = "Update carros set placa=@placa, marca=@marca where id=@id";
cmd.Parameters.Add(new SqlParameter { ParameterName = "@placa", Value = placa });
cmd.Parameters.Add(new SqlParameter { ParameterName = "@marca", Value = marca });
cmd.Parameters.Add(new SqlParameter { ParameterName = "@id", Value = id});
    
30.09.2016 / 16:07