启动第二个表单后关闭数据库连接

时间:2014-11-12 14:27:20

标签: c# mysql winforms connection-string

在我的应用程序中我有两个form.one用于登录另一个用于实际应用程序。但成功登录后,登录表单建立的数据库连接不会终止。关闭此连接的唯一方法是关闭两种形式。但是我想在登录成功后立即关闭登录表单所建立的数据库连接。这是我的代码

private void button2_Click(object sender, EventArgs e)
        {


            try
            {


            string mysqlconnection = string.Format("datasource='{0}';username=uwcentrallogin;port=3306;password=**************;Connect Timeout=20000;Command Timeout=28800", serverip.Text);
            MySqlConnection myconn = new MySqlConnection(mysqlconnection);
            MySqlCommand Selectcommand = new MySqlCommand("select * from wartif.userdata where username='" + this.adminusername.Text.Trim() + "'and adminpassword= '" + this.passwordtext.Text.Trim() + "' ; ", myconn);

            MySqlDataReader myreader;
            myconn.Open();
            myreader = Selectcommand.ExecuteReader();
            int count = 0;

            while (myreader.Read())
            {
                count = count + 1;

            }

            if (count == 1)
            {



                this.Hide();
                adminview f2 = new adminview(serverip.Text, adminusername.Text, portnumberbox.Text, defdatabase.Text);
                f2.ShowDialog();
                this.Close();
                myconn.Close();

            }

            else if (count > 1)
            {


                label4.Text = "duplicatie users exsist ";
            }

            else

            label4.Text = "Not a privileged user";
            label4.ForeColor = Color.Orange;
            errpan.BackColor = Color.Orange;


            myconn.Close();

        }

        catch 
        {


            label4.Text = "mysql database connection is not avialable";
        }



    }

    private void button3_Click(object sender, EventArgs e)
    {
        this.Close();
    }


    private void button4_Click(object sender, EventArgs e)
    {


        appconfigsave();

        label4.Text = "Your changes has been saved";
        label4.ForeColor = Color.Orange;
        errpan.BackColor = Color.Orange;

    }

1 个答案:

答案 0 :(得分:1)

添加:

 myconn.Dispose();
在你的行下方

myconn.Close();

我还建议您查看Using个数据

更多信息here

示例

        if (count == 1)
        {
            this.Hide();
            adminview f2 = new adminview(serverip.Text, adminusername.Text, portnumberbox.Text, defdatabase.Text);
            myconn.Close();
            myconn.Dispose();
            f2.ShowDialog();
            this.Close();
        }