2013-02-23 109 views
0

連接必須有效且開放。哪裏有問題 ? .net Frmework版本2.0 連接必須有效且打開。哪裏有問題 ? .net Frmework版本2.0 連接必須有效且打開。哪裏有問題 ? .net Frmework 2.0版連接必須有效且開放

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Text; 
using System.Windows.Forms; 
using System.Security.Cryptography; 
using MySql.Data.MySqlClient; 
    namespace Student_Portal_Password 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 
     public static string GetMd5Hash(string input) 
     { 
      MD5 md5Hash = MD5.Create(); 
      // Convert the input string to a byte array and compute the hash. 
      byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input)); 

      // Create a new Stringbuilder to collect the bytes 
      // and create a string. 
      StringBuilder sBuilder = new StringBuilder(); 

      // Loop through each byte of the hashed data 
      // and format each one as a hexadecimal string. 
      for (int i = 0; i < data.Length; i++) 
      { 
       sBuilder.Append(data[i].ToString("x2")); 
      } 

      // Return the hexadecimal string. 
      return sBuilder.ToString(); 
     } 
     public void check() 
     { 
      if (txtid.Text == "") 
      { 
       MessageBox.Show("Please enter Student ID ", MessageBoxIcon.Warning.ToString(), MessageBoxButtons.OK); 
      } 
      else if (txtpassword.Text == "") 
      { 
       MessageBox.Show("Please enter new password", MessageBoxIcon.Warning.ToString(), MessageBoxButtons.OK); 
      } 
     } 
     private void button1_Click(object sender, EventArgs e) 
     { 
      try 
      { 

//check(); 
      txtpassword.Text.Trim(); 
      string hash = GetMd5Hash(txtpassword.Text); 

      string db = "server=localhost;uid=root;password=usbw;database=dum;"; 
      MySqlConnection dbcon = new MySqlConnection(db); 
      MySqlCommand cmd = new MySqlCommand(db); 

      dbcon.Open(); 
      cmd.CommandText = "SELECT * FROM members;"; 
      cmd.ExecuteNonQuery(); 
          MessageBox.Show("Success!"); 
          dbcon.Close(); 
      } 
      catch (MySqlException ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 
     } 

     private void txtid_KeyPress(object sender, KeyPressEventArgs e) 
     { 
      const char Delete = (char)8; 
      e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete; 
     } 
    } 
} 
+0

有沒有我沒有看到的問題? – 2013-02-23 13:44:11

+0

是這個有效的';'? _SELECT * FROM members; _ – spajce 2013-02-23 13:47:24

+0

指向您收到此消息的代碼行。這將有助於人們縮小焦點。 – 2013-02-23 13:53:44

回答

0

一些事情;

您正在使用ExecuteNonQuery進行查詢。改爲嘗試使用ExecuteReader

您沒有爲您的DbCommand設置連接,因此執行它不會找到數據庫。
試試這個,

MySqlConnection dbcon = new MySqlConnection(db); 
string sql = "SELECT * FROM members"; 
MySqlCommand cmd = new MySqlCommand(sql, dbcon); //<-- pass connection to command 

您目前的代碼;

MySqlCommand cmd = new MySqlCommand(db); 

...傳遞連接字符串作爲要執行的SQL,並且不會將該命令與任何數據庫連接相關聯。這會給你所問的錯誤。

相關問題