简体   繁体   中英

c# how to connect and disconnect mysql database

this is the image of my form在此处输入图片说明

What I want is when I click connect button, the connection to MySQL is opened and I can use the connected database and all textboxes become disabled, if I click disconnect, I want to close the connection and user will not be able to use the connected database, and all the textboxes became enabled.

Can anyone help me with this validation !!

This the code which I have in the connect button:

connection is MySQLConnection global variable

  connection = new MySqlConnection(strConnection);

                if(connection.State == ConnectionState.Closed)
                {
                    connection.Open();
                }

and this the code which I have in disconnect button :

 if (connection.State != ConnectionState.Closed)
        {
            connection.Close();
        }

This does not work because when the disconnect button is selected the connection variable becomes null, which I do not want. I want to maintain the state of the connection variable.

you can store your connection variable in session state, I think the page is post back before you call close connection button. so variable became null ex: on Open Connection:

connection = new MySqlConnection(strConnection);

if(connection.State == ConnectionState.Closed)
{
   connection.Open();
}
Session["connection"] = connection

on Close Connection:

connection = (MySqlConnection)Session["connection"];
if (connection.State != ConnectionState.Closed)
{
   connection.Close();
}

Or you can change connection variable modifier to be static

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