简体   繁体   中英

mysql connection state in visual studio 2012 c#

I have this application to retrieve data from MySql database and I do not need to open connection to connect to database how is this possible? Usually you need to add like connection.Open() and connection.Close() . Am i missing something here? I use Visual studio 2012 and ADO.NET 4.0

Code:

public partial class Filter1 : Form
{
    public Filter1()
    {
        InitializeComponent();
    }
    private void Filter1_Load(object sender, EventArgs e)
    {
         MySqlConnection connection = new MySqlConnection("server=;database=;uid=;password=;");
         MySqlDataAdapter mySqlDataAdapter;
         DataSet DS = new Dataset();

         MySqlCommand command = connection.CreateCommand();
         command.CommandText = "SELECT * FROM table";
         mySqlDataAdapter = new MySqlDataAdapter(command.CommandText, connection);
         mySqlDataAdapter.Fill(DS.Tables[0]);
         ViewG.DataSource = DS.Tables[0];
    }

You don't need to manually open and close the connection because mySqlDataAdapter.Fill() will do it automatically for you. See the docs: enter link description here . The first paragraph under Remarks reads:

The IDbConnection object associated with the select command must be valid, but it does not need to be open. If the IDbConnection is closed before Fill is called, it is opened to retrieve data, then closed. If the connection is open before Fill is called, it remains open.

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