2016-02-19 55 views
1

我已经得到了一些代码:完全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 [email protected] and [email protected]"; 
         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。

我试过但是... “附加信息:连接必须有效且打开。”

在此先感谢!

+0

我假设你已经声明conn并连接到其他地方我们看不到,因为我没有看到他们的任何声明。 –

回答

1

当你需要使用各种任务的它始终是一个很好的做法,遵循的模式与数据库的连接创建/打开/使用/关闭/处置

所以你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; 
    } 
} 

无需关闭明确的连接,因为从使用块退出时自动关闭连接并在本地和服务器上释放释放由连接保留的资源的实例。

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

+0

upvote for'using block'我不知道为什么我在使用数据库连接时没有看到更多人使用它 –

+0

每次访问数据库时,都会打开并关闭一次以验证用户,然后打开并关闭它再次访问数据?虽然这有效,但速度会慢得多。 –

+1

@SteveWellens否,当然,您只需验证一次用户(或者如果您想重新检查以允许访问某种敏感数据)验证之后,每次需要访问数据库时,都使用此模式。连接池允许重复使用具有改进性能的连接,因此您应该始终关闭连接 – Steve

2

一旦你验证登录,您关闭连接:

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

要么离开连接打开,或重新打开它。大多数人为了速度和简单性而开放。

+1

让连接开放而不处理是一个**大错误。 – Steve

+0

所以编辑catch(MySqlException e) { MessageBox.Show(“无法连接到服务器!”); }如果我向文本框和密码框添加一个值,我会得到以下错误:其他信息:连接必须有效且打开 – Chraze

+0

@Steve - 正确,当您完成连接时关闭连接(它也会处理它)。 –

1

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

相关问题