C#附加信息:连接必须有效并且打开

时间:2016-02-19 22:25:11

标签: c#

我有一些代码:完全

            using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Text;
            using System.Threading.Tasks;
            using System.Windows;
            using System.Windows.Controls;
            using System.Windows.Data;
            using System.Windows.Documents;
            using System.Windows.Input;
            using System.Windows.Media;
            using System.Windows.Media.Imaging;
            using System.Windows.Navigation;
            using System.Windows.Shapes;
            using MySql.Data.MySqlClient;

            namespace mysql
            {
                /// <summary>
                /// Interaction logic for LoginPage.xaml
                /// </summary>
                public partial class LoginPage : Page
                {
                    private string conn;
                    private MySqlConnection connect;

                    AdminPage ap = new AdminPage();

                    public LoginPage()
                    {
                        InitializeComponent();
                    }

                    private void db_connection()
                    {
                        try
                        {
                            conn = "Server=localhost;Database=student;Uid=root;Pwd=admin;";
                            connect = new MySqlConnection(conn);
                            connect.Open();
                        }
                        catch (MySqlException e)
                        {
                            throw;
                        }
                    }

                    private bool validate_login(string user, string pass)
                    {
                        db_connection();
                        MySqlCommand cmd = new MySqlCommand();
                        cmd.CommandText = "Select * from student.admins where username=@user and password=@pass";
                        cmd.Parameters.AddWithValue("@user", user);
                        cmd.Parameters.AddWithValue("@pass", pass);
                        cmd.Connection = connect;
                        MySqlDataReader login = cmd.ExecuteReader();
                        if (login.Read())
                        {
                            connect.Close();
                            return true;
                        }
                        else
                        {
                            connect.Close();
                            return false;
                        }
                    }

                    private void btn_login_Click(object sender, RoutedEventArgs e)
                    {
                        string user = txt_admin_name.Text;
                        string pass = txt_admin_passwd.Password;
                        if (user == "" || pass == "")
                        {
                            //MessageBox.Show("Empty Fields Detected ! Please fill up all the fields");
                            txt_errormessage.Text = "Empty Fields Detected! Please fill up all the fields!";
                            return;
                        }
                        bool r = validate_login(user, pass);
                        if (r)
                        {
                            //MessageBox.Show("Correct Login Credentials.\n You will be taken the Admin Page!");
                            this.NavigationService.Navigate(ap);
                        }
                        else
                            //MessageBox.Show("Incorrect Login Credentials");
                            txt_errormessage.Text = "Incorrect Login Credentials!";
                    }
                }
            }

所以我需要一些错误处理:检查服务器连接,并检查数据库是否存在。我想写MessageBox。

我试过但......  &#34;附加信息:连接必须有效且开放。&#34;

提前致谢!

3 个答案:

答案 0 :(得分:2)

验证登录后,您将关闭连接:

if (login.Read())
{
    connect.Close();
    return true;
}
else
{
     connect.Close();
     return false;
 }

将连接保持打开状态,或重新打开它。为了速度和简单,大多数人都把它打开了。

答案 1 :(得分:1)

您需要告诉您的命令有关您的连接对象。将连接参数添加到命令   MySqlCommand cmd = new MySqlCommand(connect);

答案 2 :(得分:1)

当您需要为每种任务使用数据库连接时,遵循模式CREATE / OPEN / USE / CLOSE / DISPOSE

始终是一个好习惯。

因此,您的db_connection代码应该返回创建和打开的连接,并且永远不会使用全局变量来保留连接实例。

private MySqlConnection db_connection()
{
    try
    {
        conn = "Server=localhost;Database=student;Uid=root;Pwd=admin;";
        MySqlConnection cnn = new MySqlConnection(conn);
        cnn.Open();
        return cnn;
    }
    catch (MySql.Data.MySqlClient.MySqlException ex)
    {
        switch (ex.Number)
        {
            case 0: MessageBox.Show("Cannot connect to server!"); break;
        }
        retur null;
    }
}

现在,想要使用您的方法的代码可以用更加资源友好的方式编写

private bool validate_login(string user, string pass)
{
    using(MySqlConnection cnn = db_connection())
    using(MySqlCommand cmd = new cnn.CreateCommand())
    {
         cmd.CommandText = ".....";
         cmd.Parameters.AddWithValue("@user", user);
         cmd.Parameters.AddWithValue("@pass", pass);
         using(MySqlDataReader login = cmd.ExecuteReader())
            return login.HasRows;
    }
}

无需显式关闭连接,因为从using块的退出会自动关闭连接并释放实例,从而在本地和服务器上释放连接所保留的资源。

当然,当您需要再次查询数据库时,应使用相同的模式。