简体   繁体   中英

Why does my C# application still retrieves data from MySql without using connection.Open()

I have tried to retrieve data from my table on MySql using my C# application. So I applied the usual connection methods in order to connect my c# application to my MySql database and also called to appropriate methods to retrieve the data from the table and then display it on my application. However, I noticed that by just using the following code:

conString = "server=localhost;user id=" + user + ";database=db;password="+pass;
connection = new MySqlConnection(conString);
DataTable table = new DataTable();
MySqlDataAdapter adapter = new MySqlDataAdapter("SELECT * FROM users", connection);
adapter.Fill(table);
dataGridView1.DataSource = table;

I can retrieve the data from the table and display, without using the following code:

connection.Open();

what is the purpose to use connection.Open() if I only need the following code to retrieve data? When will I need to use connection.Open() ?

Do I need to use connection.Open() only when I sending information from my application to mysql but when I want to get/retrieve information from MySql then I don't need to use connection.Open() , is this correct?

Since the intention of calling adapter.Fill(table);is to retrieve data from the database I would highly expect that the Fill method opens the connection if it isn't already.

You would only need to explicitly call Open if you intend to operate on the connection directly instead of through helper classes like MySqlDataAdapter for example. You can of course open it whenever you feel like.

I would, however, suggest you put the connection in a using statement to ensure that it's closed and disposed of when you are done with it:

using (var connection = new MySqlConnection(conString))
{
    DataTable table = new DataTable();
    MySqlDataAdapter adapter = new MySqlDataAdapter("SELECT * FROM users", connection);
    adapter.Fill(table);
    dataGridView1.DataSource = table; 
}
// Now you are sure the connection is closed and being properly garbage collected

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM