简体   繁体   English

c#如何连接和断开mysql数据库

[英]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.我想要的是当我点击连接按钮时,到 MySQL 的连接被打开,我可以使用连接的数据库并且所有文本框都被禁用,如果我点击断开连接,我想关闭连接,用户将无法使用连接数据库,并且所有文本框都已启用。

Can anyone help me with this validation !!任何人都可以帮助我进行此验证!

This the code which I have in the connect button:这是我在连接按钮中的代码:

connection is MySQLConnection global variable连接是 MySQLConnection 全局变量

  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:所以变量变成空 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或者您可以将连接变量修饰符更改为静态

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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