为什么我的C#应用​​程序仍不使用connection.Open()从MySql检索数据

我试图使用C#应用程序从MySql上的表中检索数据。因此,为了将c#应用程序连接到MySql数据库,我应用了通常的连接方法,还调用了适当的方法以从表中检索数据,然后将其显示在我的应用程序上。但是,通过使用以下代码,我注意到了这一点:

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;

我可以从表和显示中检索数据,而无需使用以下代码:

connection.Open();

那么,如果我只需要以下代码来检索数据,那么使用connection.Open()有什么意义呢?什么时候需要使用connection.Open()?

我是否需要使用连接。仅当我将信息从应用程序发送到mysql时才需要Open(),但是当我想从MySql中获取信息时,则不需要使用connection.Open(),这是正确的吗?

评论
  • ysunt
    ysunt 回复

    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