2016-02-19 64 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);

相關問題