Connection to MySQL from .NET using SSH.NET Library

前端 未结 2 1975
梦谈多话
梦谈多话 2020-12-04 00:06

I am developing a web page (ASP.NET/ C#) that queries (MySQL) database on a remote server over SSH. I am using those two libraries (mysql-connector-net-6.9.7) and (

2条回答
  •  天命终不由人
    2020-12-04 00:47

    Most of the code below is self explanatory. Still I have put the needful comments. I was able to connect to the MySql database with the code below. I had used SSH library from here and MySql connector for .NET.

    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...");
        }
    }
    

提交回复
热议问题