2015-06-22 152 views
0

我想在VirtualBox上連接到我的SqlDatabase。我嘗試不同的方式來做到這一點,但不幸的是,它不起作用。我添加了一個MySql.DataMySql.Data.MySqlClientc#使用MySQL連接到數據庫

 MySqlConnection connection; 
     string server; 
     string database; 
     string uid; 
     string password; 
     string port; 
     server = "192.168.1.21"; 
     port = "3306"; 
     database = "terminal1"; 
     uid = "root"; 
     password = "pass"; 
     string connectionString; 
     connectionString = "SERVER=" + server + ";" + "PORT=" + port +   ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";" + "Pooling=false"; 
     connection = new MySqlConnection(connectionString); 


     try 
     { 
      connection.Open(); 
      label1.Text = "NET - OK"; 
     } 
     catch (MySqlException ex) 
     { 
      //0: Cannot connect to server. 
      //1042: Unable to connect to any of the specified MySQL hosts. 
      //1045: Invalid user name and/or password. 
      switch (ex.Number) 
      { 
       case 0: 
        MessageBox.Show("Cannot connect to server. Contact administrator"); 
        break; 
       case 1042: 
        MessageBox.Show("Unable to connect to any of the specified MySQL hosts"); 
        break; 
       case 1045: 
        MessageBox.Show("Invalid username/password, please try again"); 
        break; 
       default: 

         label1.Text = "NET - ERROR"; 

        break; 
      } 

     } 

任何人都可以幫忙嗎?

編輯: 該程序顯示錯誤1042:無法連接到任何指定的MySQL主機。

+0

不工作怎麼樣? 'mysql'服務器是否接受來自其他主機的連接而不是本地主機? – Jite

+0

在PHP我可以通過IP連接,所以我認爲服務器接受來自其他主機的連接,而不是本地主機 – Wojtek

+0

請...不要使用標準點網絡名稱 –

回答

0

我有這個問題struggeld自己,這是我的sqlclass:

namespace Chat 
{ 
    internal class DBConnect 
    { 
     private MySqlConnection _connection = new MySqlConnection(); 
     private MySqlConnection _register = new MySqlConnection(); 
     private MySqlConnection _userdata = new MySqlConnection(); 
     private string _server; 
     private string _database; 
     private string _uid; 
     private string _password; 
     public String MessageRecieved; 
     //private string _table = "testconnectie"; 
     private string _port; 
     //private bool succes = false; 


     //Constructor 
     public DBConnect() 
     { 
      InitializeChat(); 
      InitializeRegister(); 
     } 

     //Initialize values 
     public void InitializeChat() 
     { 
      _server = "localhost"; 
      _port = "3307"; 
      _database = "test"; 
      _uid = "root"; 
      _password = "usbw"; 


      string connectionString = "Server=" + _server + ";" + "Port=" + _port +";" + "Database=" + 
           _database + ";" + "Uid=" + _uid + ";" + "Pwd=" + _password + ";"; 

      _connection = new MySqlConnection(connectionString); 
     } 

     public void InitializeUserData() 
     { 
      _server = "localhost"; 
      _port = "3307"; 
      _uid = "root"; 
      _password = "usbw"; 


      string connectionString = "Server=" + _server + ";" + "Port=" + _port + ";" + "Database=" + 
           _database + ";" + "Uid=" + _uid + ";" + "Pwd=" + _password + ";"; 

      _connection = new MySqlConnection(connectionString); 
     } 

     public void InitializeRegister() 
     { 
      _server = "localhost"; 
      _port = "3307"; 
      _database = "testlogin"; 
      _uid = "root"; 
      _password = "usbw"; 


      string registerString = "Server=" + _server + ";" + "Port=" + _port + ";" + "Database=" + 
           _database + ";" + "Uid=" + _uid + ";" + "Pwd=" + _password + ";"; 

      _register = new MySqlConnection(registerString); 
     } 

     public bool OpenConnection() 
     { 
      try 
      { 
       _register.Open(); 
       return true; 
      } 
      catch (MySqlException ex) 
      { 
       switch (ex.Number) 
       { 
        case 0: 
         MessageBox.Show("Cannot connect to server"); 
         break; 

        case 1042: 
         MessageBox.Show("Unable to connect to any of the specified MySQL hosts"); 
         break; 

        case 1045: 
         MessageBox.Show("Invalid username/password"); 
         break; 
       } 
       return false; 

      } 

     } 

     public void Select() 
     { 
      string selectquery = "SELECT * FROM testconnectie"; 

      MySqlCommand cmd = new MySqlCommand(selectquery, _connection); 

      MySqlDataReader dataReader = cmd.ExecuteReader(); 

      _messagelist.Clear(); 
      while (dataReader.Read()) 
      { 
       _messagelist.Add(dataReader["time"] + "  "); 
       _messagelist.Add(dataReader["text"] + "\r\n"); 
      } 

      dataReader.Close(); 


      MessageRecieved = _messagelist.ToString(); 

     } 

     public void Insert(string textvalue) 
     { 
      //DateTime dt = DateTime.Parse("6/22/2009 07:00:00 AM"); 

      //dt.ToString("H:mm"); // 7:00 // 24 hour clock 

      //var now = DateTime.Now; 
      //var minutes = now.Minute; 
      //var hour = now.Hour; 
      //var time = now; 

      string time = DateTime.Now.ToString("HH:mm:ss"); 

      string insertquery = "INSERT INTO testconnectie(time, text) VALUES ('"+time+"','"+textvalue+"')"; 

      try 
      { 
       MySqlCommand cmd = new MySqlCommand(insertquery, _connection); 

       cmd.ExecuteNonQuery(); 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show("Error(1)" + ex); 
      } 
     } 

     private void Update() 
     { 
      string updatequery = "UPDATE tabelnaam SET waarde='', waarde'' WHERE waarde=''"; 

      MySqlCommand cmd = new MySqlCommand(); 

      cmd.CommandText = updatequery; 
      cmd.Connection = _connection; 

      cmd.ExecuteNonQuery(); 
     } 

     private void Delete() 
     { 
      string deletequery = "DELETE FROM tabelnaam WHERE waarde=''"; 

      MySqlCommand cmd = new MySqlCommand(deletequery, _connection); 
      cmd.ExecuteNonQuery(); 
     } 

     public bool CloseConnection() 
     { 
      try 
      { 
       _connection.Close(); 
       return true; 
      } 
      catch (MySqlException ex) 
      { 
       MessageBox.Show(ex.Message); 
       return false; 

      } 

     } 


     public void Backup() 
     { 
      try 
      { 
       DateTime Time = DateTime.Now; 
       int year = Time.Year; 
       int month = Time.Month; 
       int day = Time.Day; 
       int hour = Time.Hour; 
       int minute = Time.Minute; 
       int second = Time.Second; 
       int millisecond = Time.Millisecond; 

       //Save file to C:\ with the current date as a filename 
       string path; 
       path = "C:\\ChatBackup" + year + "-" + month + "-" + day + 
      "-" + hour + "-" + minute + "-" + second + "-" + millisecond + ".sql"; 
       StreamWriter file = new StreamWriter(path); 


       ProcessStartInfo psi = new ProcessStartInfo(); 
       psi.FileName = "Database Backup"; 
       psi.RedirectStandardInput = false; 
       psi.RedirectStandardOutput = true; 
       psi.Arguments = string.Format(@"-u{0} -p{1} -h{2} {3}", 
      _uid, _password, _server, _database); 
       psi.UseShellExecute = false; 

       Process process = Process.Start(psi); 

       string output; 
       output = process.StandardOutput.ReadToEnd(); 
       file.WriteLine(output); 
       process.WaitForExit(); 
       file.Close(); 
       process.Close(); 
      } 
      catch (IOException ex) 
      { 
       MessageBox.Show("Error , unable to backup! " + ex); 
      } 
     } 



    } 

} 

希望這有助於它可能是有點大,但只是使用功能,你需要

你可以做的是使用在項目屬性中設置存儲所有連接數據。

所以你可以把serverIp,Port,Database,Uid和密碼放在de設置標籤中。

你可以打電話給他們這樣的:Properties.Settings.Default.serverIp

它的輕鬆一點所以最後你可以這樣做:

string serverIp = Properties.Setting.Default.serverIp; 
string port = Properties.Setting.Default.port; 
string username = Properties.Setting.Default.Uid; 

等。

也可能試圖改變UID在你的ConnectionString TYO Uid

你也捕捉到了異常,但你不使用它,在這種情況下,默認應顯示爲exception,所以你可以把它理解。你可以這樣做:

label1.Text = "Error: " + ex.Message; 
0

你必須使用DBLinq將mysql集成到C#中。

請訪問DBLinq

+0

你爲什麼要使用它?我的意思是Mysql.Data工作很好 –