Difference between mysqlconnection and using (mysqlconnection)?

0

My question is what is the difference between the following connections?

Conexion Mysql without USING

MySqlConnection databaseConnection = new MySqlConnection("//CADENA DE XCONEXION");

// CODE;

MYSQL Connection with USING

using (NpgsqlConnection cnx = new pgsqlConnection("//CADENA DE CONEXION"))
        {
            //CODIGO 
        }

The main difference that I have observed that with the first connection string if you do not close it you can not execute MysqlCommand, DataReader, etc. but instead with the second connection string you can execute MysqlCommand, DataReader, etc. need to close the connection chain

    
asked by Eduardo Zapata 19.12.2018 в 17:02
source

2 answers

2

By using the block using what you achieve is to make sure that the pool de conexiones actuates which is more performant when you create and destroy connections since there is an active pool that is reused

5.3 Using Connector / NET with Connection Pooling

the using ensures that you release the connection object correctly, so it is recommended that you use it

With both you can run get a MySqlDataReader, whether you use

string connstring = "connection string";  
MySqlConnection cn = new MySqlConnection(connstring); 
cn.Open();  

string sql = "SELECT campo1, campo2, campo3 FROM Tabla";  
MySqlCommand cmd = new MySqlCommand(query, cn);   

MySqlDataReader reader = cmd.ExecuteReader();  

if (reader.Read())  
{  
    //codigo
}  

cn.Close();

or that you do it

string connstring = "connection string";  
using (MySqlConnection cn = new MySqlConnection(connstring)) {  
    cn.Open();  

    string sql = "SELECT campo1, campo2, campo3 FROM Tabla";  
    MySqlCommand cmd = new MySqlCommand(query, cn);  

    MySqlDataReader reader = cmd.ExecuteReader();  

    while(reader.Read())  
    {  
        //codigo
    }  

}

In both ways you can loop the reader

    
answered by 19.12.2018 в 17:31
0

Using what you do is to execute Dispose() when you finish executing your code block.

It would be equivalent to doing:

var connection = new MySqlConnection("...");

try 
{
    // código
}
catch(Exception ex)
{
    // manejo de excepción
}
finally
{
    connection.Dispose();
}
    
answered by 19.12.2018 в 18:21