使用 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中文网其他相关文章!