-4

I have a SQL database being locally hosted that keeps track of stock, I'm trying to get the SQL command "UPDATE stock SET cantidad = 530 WHERE id = 0" through using a C# Windows form application. But I'm having no changes made on the codebase

For this, I've made a function "setCantidad", but it isn't working. I'm getting no errors, just no changes in the codebase. All the other functions, which are made similarly to this one, work well. The SQL command, when inputted directly into the codebase, works well.

Here's the function

public void setCantidad(int valorActualizado, int indice)
{
    Conexion miConexion = new Conexion();
    conectar = miConexion.GetConnection();
    conectar.Open();
    sql = "UPDATE stock " + "SET cantidad = " + valorActualizado + " WHERE id = " + indice;
    MySqlCommand comando = new MySqlCommand(sql, conectar);
    conectar.Close();
} 

The value of the SQL variable is sql = UPDATE stock SET cantidad = 530 WHERE id = 0 once it reaches conectar.Close, so I doubt it's that.

7
  • where do you execute MySqlCommand? Commented Sep 2 at 19:32
  • comando.ExecuteNonQuery() is required before closing the connection. Commented Sep 2 at 19:43
  • 4
    Unrelated, but this is also a good time to start using parameterized queries. Commented Sep 2 at 19:43
  • The following may be of interest: stackoverflow.com/a/68510196/10024425 (see code block for HelperMySql.cs) Commented Sep 2 at 19:53
  • Okay the issue has been solved. I wasn't using a reader to actually read the MySqlCommand. I deserve to be put in front of a firing squad Commented Sep 2 at 20:02

1 Answer 1

2

You need to actually execute the command, not just create it. It won't run by itself.

You should also parameterize your query, and have using on any disposable objects.

public void setCantidad(int valorActualizado, int indice)
{
    Conexion miConexion = new Conexion();
    using var conectar = miConexion.GetConnection();
    conectar.Open();
    const string sql = @"
UPDATE stock
SET cantidad = @valorActualizado
WHERE id = @indice;
";
    using var comando = new MySqlCommand(sql, conectar);
    comando.Parameters.Add("@indice", SqlDbType.Int).Value = indice;
    comando.Parameters.Add("@valorActualizado", SqlDbType.Int).Value = valorActualizado;
    comando.ExecuteNonQuery();
}

Consider also using async and await if possible.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.