Update SQL Server through Visual Studio ASP.NET web forms

1

I'm trying to do update in a DB, but I'm not making the changes to that command. When I do it in the direct query of SQL server it works, but when I do it from my application it does not do the update .

This is the query in SQL Server:

update cliente set telefono = '864346', cedula = '8826537',
nombre = 'Lucho', direccion = 'Cll 60 # 15 - 45'
where cedula = '123456789' 
and nombre = 'Luis Ocampo'
and telefono = '3116085275'
and direccion = 'sddferr';

This is the code from Visual Studio:

string s = System.Configuration.ConfigurationManager.ConnectionStrings["cadenaconexion1"].ConnectionString;
            SqlConnection conexion = new SqlConnection(s);
            conexion.Open();
            SqlCommand comando = new SqlCommand("update cliente set " + 
                                 "cedula = '" + ccliente.Text + "', nombre = '" +
                                 ncliente.Text + "', telefono = '" + ctelefono.Text +
                                 "', direccion = '" + cdireccion.Text + "' where cedula = '" + 
                                 ccliente.Text + "' and nombre = '" +
                                 ncliente.Text + "' and telefono = '" + 
                                 ctelefono.Text + "' and direccion = '" + 
                                 cdireccion.Text + "'", conexion);

            ccliente.Text = string.Empty;
            ncliente.Text = string.Empty;
            ctelefono.Text = string.Empty;
            cdireccion.Text = string.Empty;

            msgerror.Text = "Información actualizada con exito";

            conexion.Close();

I do not know if I'll be eating something, or if I misunderstood the process that has to be done with the Texbox to update the info.

I remain attentive, please, I hope you can help me. Thanks.

    
asked by Edward Sc 07.11.2018 в 05:30
source

2 answers

2

The main problem is that you are assigning a query to the command, but you never send it to the database engine. In other words, you do not execute the command.

To send the UPDATE, execute the ExecuteNonQuery method, for example:

comando.ExecuteNonQuery();

Once this has been clarified. I'm going to take the audacity to leave you some tips . There may be other ways of doing it that differ from mine. It remains in you to investigate which is the most appropriate and fits your project.

  • When doing an UPDATE of a record, you must ALWAYS do it by ID that corresponds to him Never using the current values as conditions.

  • You are using the same values for the WHERE you want to assign. Here more than a tip, I highlight an error.

  • You should avoid using concatenation in queries since they can cause many inconveniences. For that you can use for example SqlParameterCollection . In this case you are not working with dates or complex data, but in the future it will be indispensable. Apart from that you expose yourself to injection of SQL . exist other methods, you can research which one is best suited to your use.

  • Always make inquiries within a Using. Something like this:
using (SqlConnection connection = new SqlConnection(
  "Integrated Security=SSPI;Initial Catalog=Northwind"))
{
    connection.Open();      
    // Pool A is created.
}

Why use "using" in the code?

In C # there are some objects that use system resources. Which must be removed, closed, emptied and disposed of, etc. In C # you can write the code to Create a new instance in the resource, use it, close it, empty it, discard it. Or, on the other hand, you can simply use this statement usingblock in which the created object is closed, emptied and discarded and the resources can be used again by other processes. This ensures that the framework will take the best measures for each process.

  • Add a try-catch to handle the exceptions.
  • Avoid placing too many abstract names to the variables and elements. For example, replace 'cclient' with 'customerCell' or 'CustomerCard' etc ..
  • Respect the tabulation in the code. It is very important to try keep a code clean and clear. In this way it will be more easy to find the errors and understand more complex codes quickly.
  • I usually use ExecuteNonQuery() returns only the number of rows affected by an insertion, update or deletion. You can use it to know if the update was made correctly.

I leave the code respecting your conditions in the query, but making some other improvements such as those mentioned. You must replace the values assigned to the parameters for the conditions. I did not know where you were taking them, since you were using the same ones you assigned.

using (SqlConnection conexion = new SqlConnection(
  ConfigurationManager.ConnectionStrings["cadenaconexion1"].ConnectionString))
{
    try
    {
        conexion.Open();      

        cmd.CommandType = System.Data.CommandType.Text;
        cmd.Connection = conexion;
        cmd.CommandText = "update cliente set telefono = @telefono, cedula = @cedula, nombre = @nombre, direccion = @direccion where cedula =  @cedulaWhere and nombre = @nombreWhere and telefono = @telefonoWhere and direccion = @direccionWhere";

        //Vamos a agregar los valores como parámetros para evitar la concatenación en la consulta.
        //Valores con los que se van a actualizar los campos
        cmd.Parameters.AddWithValue("@cedula",ccliente.text);
        cmd.Parameters.AddWithValue("@nombre", ncliente.text);
        cmd.Parameters.AddWithValue("@telefono", ctelefono.text);
        cmd.Parameters.AddWithValue("@direccion", cdireccion.text)
        //Valores para las condiciones.
        cmd.Parameters.AddWithValue("@cedulaWhere",'123456789');
        cmd.Parameters.AddWithValue("@nombreWhere", 'Luis Ocampo');
        cmd.Parameters.AddWithValue("@telefonoWhere", '3116085275');
        cmd.Parameters.AddWithValue("@direccionWhere", 'sddferr');

        int result = cmd.ExecuteNonQuery();
        // Ahora en result tenemos la cantidad de filas afectadas. 
       // En base a eso podemos determinar si hubo exito al realizar la actualizacion. En ese caso deberia ser > 0 por ej.

    }
    catch(Exception ex)
    { 
        // aquí puedes manejar las excepciones. Mostrarlas al usuario o lo que desees.
    }
}
    
answered by 07.11.2018 / 06:42
source
1

You are assigning a SQL text to the command, but you never send it to the database engine.

To send the update , execute the method ExecuteNonQuery , for example:

comando.ExecuteNonQuery();

Warning

The way you build your sentence, concatenating values entered by the user, your application is vulnerable to attacks by < em> SQL injection . Investigate the sending of parameterized statements to the database to avoid this problem.

    
answered by 07.11.2018 в 06:30