Updating a datagrid with mysql connection

Asked

Viewed 56 times

1

I can’t update a table from a database linked to a datagrid. When I change the data in the datagrid cells, although these appear changed during the debug, at the end the table is not updated. Does anyone know what’s missing in the code?

private static OdbcConnection CreateConnection()
{
    return new OdbcConnection("driver= {MySQL ODBC 5.1 Driver};server=192.168.20.29; database=yyyy; uid=esta; password=1234; option = 3 ");
}
using (OdbcConnection connection = CreateConnection())
{
string CmdText = "update lojas set Bloqueado =@bloqueador, DataFim = @DataFim, Nome = @Nome where Id =@Id";

OdbcCommand cm = new OdbcCommand(CmdText, connection);
cm.CommandType = CommandType.Text;
connection.Open();

cm.Parameters.AddWithValue("@Id", grid_lic.CurrentRow.Cells[0].Value);
cm.Parameters.AddWithValue("@bloqueador",grid_lic.CurrentRow.Cells[3].Value);
cm.Parameters.AddWithValue("@DataFim",grid_lic.CurrentRow.Cells[4].Value);
cm.Parameters.AddWithValue("@Nome",grid_lic.CurrentRow.Cells[6].Value);

cm.ExecuteNonQuery();

}

  • See if this helps you.. http://stackoverflow.com/questions/15526067/c-sharp-refresh-datagridview-when-updating-or-inserted-on-another-form

  • Or this http://stackoverflow.com/questions/21299016/how-to-refresh-or-show-immediately-in-datagridview-after-inserting

  • Is that code on a button? If not, where it is fired?

1 answer

1

I advise using Mysql.data you can catch the dll here, using it will be easier, follow example of connection with the bank and update of the same:

bdConn = new MySqlConnection("Persist Security Info=False;server=SERVIDOR;database=BANCO;uid=LOGIN;pwd=SENHA");
try
{
    bdConn.Open();
    MySqlCommand updateCommand = new MySqlCommand("UPDATE lojas SET Bloqueado =@bloqueador, DataFim = @DataFim, Nome = @Nome WHERE Id =@Id", bdConn);
    updateCommand.Parameters.AddWithValue("@Id", grid_lic.CurrentRow.Cells[0].Value);
    updateCommand.Parameters.AddWithValue("@bloqueador",grid_lic.CurrentRow.Cells[3].Value);
    updateCommand.Parameters.AddWithValue("@DataFim",grid_lic.CurrentRow.Cells[4].Value);
    updateCommand.Parameters.AddWithValue("@Nome",grid_lic.CurrentRow.Cells[6].Value);
    updateCommand.ExecuteNonQuery();
}
catch (MySqlException ex)
{
    MessageBox.Show(ex.Message);
}
finally
{
    //Fechar conexão aberta
    bdConn.Close();
}

It is advisable to open and close the connection for all queries you will be making (it is also advisable to carry out as many queries as you can with this connection to save time in the process of opening and closing the connection with the bank).

  • but it’s not exactly, except for the exception treatment, what happens in the implementation of Dispose Pattern through using?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.