使用SSH.NET 庫從.NET 連接到MySQL
問題:
An ASP.NET/C# 網頁嘗試使用Renci.SshNet 和mysql-connector-net 函式庫透過SSH 連線查詢遠端伺服器上的MySQL 資料庫。但是,程式碼並未從資料庫中檢索任何資料。
程式碼片段:
C# 程式碼嘗試建立 SSH 連線、轉送連接埠和然後連接MySQL資料庫。但是,它無法從資料庫中檢索任何資料。
<code class="csharp">using(var client = new SshClient("ssh server id", "sshuser", "sshpassword")) // establishing ssh connection to server where MySql is hosted { client.Connect(); if (client.IsConnected) { var portForwarded = new ForwardedPortLocal("127.0.0.1", 3306, "127.0.0.1", 3306); client.AddForwardedPort(portForwarded); portForwarded.Start(); using (MySqlConnection con = new MySqlConnection("SERVER=127.0.0.1;PORT=3306;UID=someuser;PASSWORD=somepass;DATABASE=Dbname")) { using (MySqlCommand com = new MySqlCommand("SELECT * FROM cities", con)) { com.CommandType = CommandType.CommandText; DataSet ds = new DataSet(); MySqlDataAdapter da = new MySqlDataAdapter(com); da.Fill(ds); foreach (DataRow drow in ds.Tables[0].Rows) { Console.WriteLine("From MySql: " + drow[1].ToString()); } } } client.Disconnect(); } else { Console.WriteLine("Client cannot be reached..."); } }</code>
解決方案:
要解決此問題,可以對程式碼進行以下修改:
MySqlConnectionStringBuilder connBuilder = new MySqlConnectionStringBuilder(); connBuilder.AllowBatch = true; connBuilder.Server = "portal.RemoteServer.edu"; connBuilder.Port = 3306; connBuilder.UserID = "RemoteServerUsername"; connBuilder.Password = "RemoteServerPassword"; connBuilder.Database = "DatabaseName";
修改程式碼:
<code class="csharp">using(var client = new SshClient("portal.RemoteServer.edu", "RemoteServerUsername", "RemoteServerPassword")) // establishing ssh connection to server where MySql is hosted { client.Connect(); if (client.IsConnected) { var portForwarded = new ForwardedPortLocal("127.0.0.1", 3306, "127.0.0.1", 3306); client.AddForwardedPort(portForwarded); portForwarded.Start(); using (MySqlConnection con = new MySqlConnection(connBuilder.ConnectionString)) { using (MySqlCommand com = new MySqlCommand("SELECT * FROM Clients", con)) { com.CommandType = CommandType.CommandText; DataSet ds = new DataSet(); MySqlDataAdapter da = new MySqlDataAdapter(com); da.Fill(ds); foreach (DataRow drow in ds.Tables[0].Rows) { Console.WriteLine("From MySql: " + drow[1].ToString()); } } } client.Disconnect(); } else { Console.WriteLine("Client cannot be reached..."); } }</code>
以上是以下是幾本符合文章內容的英文問答類標題: * Why Am I Unable to Retrieve Data from a MySQL Database Through SSH.NET? * Troubleshooting MySQL Connection Issues with SSH.NET: A Case Study * How to Correctly Connect to a Rem的詳細內容。更多資訊請關注PHP中文網其他相關文章!