How to execute sql statement that is stored in a string in C #

1

I have the following SQL string in a string to update tables from textBox.

string actualizar = "update pelicula set nombre_pelicula = " + txtnombre.Text.Trim() + " , web_pelicula = " + txtweb.Text.Trim() + " , descripcion = " + txtdescripcion.Text.Trim() + " , anio = " + txtanio.Text.Trim() + "where id_pelicula = " + txtid.Text.Trim();
                SqlCommand comando = new SqlCommand(actualizar, conexion);

                SqlDataReader dr = comando.ExecuteReader();


                //comando.ExecuteNonQuery();
                if (dr.Read())
                {
                    MessageBox.Show("Se actualizo correctamente");
                    conexion.Close();
                }

But with the time to modify the elements I get the following error:

where line 84 is:

SqlDataReader dr = comando.ExecuteReader();

Also when I replace this line with:

comando.ExecuteNonQuery();

Keep giving the error

    
asked by Ibarra Emiliano 14.11.2018 в 01:01
source

2 answers

3

You have to use parameters, it is a pessimistic practice to concatenate the values in the string

string actualizar = @"update pelicula set nombre_pelicula = @nombrepelicula, web_pelicula = @web, descripcion = @descripcion, anio = @anio
                        where id_pelicula = @id";
SqlCommand comando = new SqlCommand(actualizar, conexion);
comando.Parameters.AddwithValue("@nombrepelicula", txtnombre.Text.Trim());
comando.Parameters.AddwithValue("@web", txtweb.Text.Trim());
comando.Parameters.AddwithValue("@descripcion", txtdescripcion.Text.Trim());
comando.Parameters.AddwithValue("@anio", txtanio.Text.Trim());
comando.Parameters.AddwithValue("@id", txtid.Text.Trim());

comando.ExecuteNonQuery();

Also it is a update the ExecuteNonQuery() is used the reader only applies to select

    
answered by 14.11.2018 / 01:16
source
0

in the fields of your table that are varchar or nvarchar type or text, when executing the query, it must be between single quote or apostofre ''.

Everything that is text in your query must contain ''.

Try it this way:

string actualizar = "update pelicula set nombre_pelicula = '" + txtnombre.Text.Trim() + "' , web_pelicula = '" + txtweb.Text.Trim() + "' , descripcion = '" + txtdescripcion.Text.Trim() + "' , anio = " + txtanio.Text.Trim() + "where id_pelicula = " + txtid.Text.Trim();
            SqlCommand comando = new SqlCommand(actualizar, conexion);

            SqlDataReader dr = comando.ExecuteReader();


            comando.ExecuteNonQuery();
            MessageBox.Show("Se actualizo correctamente");
            conexion.Close();
    
answered by 14.11.2018 в 01:16