为什么我的C#应用​​程序仍然不使用connection.Open()从MySql检索数据 [英] Why does my C# application still retrieves data from MySql without using connection.Open()

查看:139
本文介绍了为什么我的C#应用​​程序仍然不使用connection.Open()从MySql检索数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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();

如果我只需要以下代码来检索数据,使用connection.Open()的目的是什么?我什么时候需要使用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() ?

仅当我从应用程序向mysql发送信息时才需要使用connection.Open(),但是当我想从MySql获取/检索信息时我不需要使用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?

推荐答案

由于调用adapter.Fill(table);的意图是从数据库中检索数据,因此我非常希望Fill方法打开该连接(如果没有)已经.

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.

仅当您打算直接在connection上进行操作而不是通过诸如MySqlDataAdapter之类的帮助程序类时,才需要显式调用Open.当然,您可以随时打开它.

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.

但是,我建议您将连接放在using语句中,以确保在完成连接后将其关闭并丢弃:

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

这篇关于为什么我的C#应用​​程序仍然不使用connection.Open()从MySql检索数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆