How to close mysql connections in C #

1

Running the code below:

    DataSet bdDataSet;
    MySqlConnection conexao;

    public void inserir()
    {
        bdDataSet = new DataSet();

        conexao = new MySqlConnection("Server=localhost; Database=teste; Uid=; Pwd=");

        try
        {
            conexao.Open();
            Console.WriteLine("conectou");
        }catch{
            Console.WriteLine("Erro ao conectar");
        }

        if(conexao.State == ConnectionState.Open ){
            Console.WriteLine("conexao aberta");
            MySqlCommand commS = new MySqlCommand("INSERT INTO usuario VALUES('teste', 'teste')", conexao);
            commS.BeginExecuteNonQuery();
        }
    }

The registry is entered normally, the problem is that if after the excerpt:

MySqlCommand commS = new MySqlCommand("INSERT INTO usuario VALUES('teste', 'teste')", conexao);
commS.BeginExecuteNonQuery();

If I run conexao.Close() to close the connection it does not execute the command, as if it did not give commit in the query and insert is not done, what can it be?     

asked by anonymous 24.07.2014 / 01:43

3 answers

2

MySqlCommand.BeginExecuteNonQuery executes a asynchronous statement in relation to the database. data .

This means that the query is not executed as soon as the command is given, but at the most opportune time, outside the current execution stream.

To solve your problem, you can simply use ExecuteNonQuery or call the end of the asynchronous execution before closing your connection:

IAsyncResult myResult = myCommand.BeginExecuteNonQuery(null, null);
...
rowsAffected = myCommand.EndExecuteNonQuery(myResult);
    
24.07.2014 / 06:13
2

Run the query as shown below:

DataSet bdDataSet;
MySqlConnection conexao;

public void inserir()
{
    bdDataSet = new DataSet();

    conexao = new MySqlConnection("Server=localhost; Database=teste; Uid=; Pwd=");

    try
    {
        conexao.Open();
        Console.WriteLine("conectou");

        MySqlCommand commS = new MySqlCommand("INSERT INTO usuario VALUES('teste', 'teste')", conexao);
        commS.ExecuteNonQuery();

    }catch{
        Console.WriteLine("Erro ao conectar ou ao executar comando SQL");
    } finally {
        if(conexao != null && conexao.State == ConnectionState.Open ){
            conexao.Close();
        }
    }
}

Note that to execute the query the ExecuteNonQuery() command is used. In addition, the connection is closed in finally , so that it is guaranteed to be closed.

    
24.07.2014 / 13:01
0

I think you can check if MySQL is configured with autocommit or not.

Take a look at this link MySqlConnection . There is information and code sample how to work with manual commit.

    
24.07.2014 / 04:57