Home >Database >Mysql Tutorial >How to Connect to a Remote MySQL Database via SSH.NET in .NET?
Connecting to MySQL from .NET via SSH.NET
Problem:
Users encounter Schwierigkeiten when attempting to retrieve data from a MySQL database situated on a remote server over SSH using a combination of the MySQL Connector/NET and SSH.NET libraries. Despite having established an SSH connection, the code fails to produce results from database queries.
Solution:
To address this issue, it is crucial to configure the forwarded port correctly. The code below offers a refined approach:
<code class="csharp">using(var client = new SshClient("ssh server id", "sshuser", "sshpassword")) // establish SSH connection to server hosting MySQL { 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>
In this updated code:
This revised code effectively connects to the database, retrieves data, and displays it, providing a reliable mechanism for accessing a remote MySQL database through SSH in .NET applications.
The above is the detailed content of How to Connect to a Remote MySQL Database via SSH.NET in .NET?. For more information, please follow other related articles on the PHP Chinese website!