我正在开发一个网页(ASP.NET/C#),通过 SSH 查询远程服务器上的(MySQL)数据库。我正在使用这两个库(mysql-connector-net-6.9.7)和(Renci.SshNet.dll)。
我可以通过 SSH 连接使用远程服务器上的 MySQL Workbench 访问 MySQL 数据库:
"门户网站.RemoteServer.edu:22“ 使用 ”远程服务器用户名" and
"远程服务器密码".
这是我的 C# 代码,它不会从远程服务器上的 Clients 表返回任何数据:
MySqlConnectionStringBuilder connBuilder = new MySqlConnectionStringBuilder();
connBuilder.AllowBatch = true;
connBuilder.Server = "127.0.0.1";
connBuilder.Port = 3306;
connBuilder.UserID = "LocalHostUserID";
connBuilder.Password = "LocalHostPassword";
connBuilder.Database = "DatabaseName";
var auth =
new PasswordAuthenticationMethod("RemoteServerUsername", "RemoteServerPassword");
ConnectionInfo conInfo =
new ConnectionInfo("portal.RemoteServer.edu", "RemoteServerUsername", auth);
using (SshClient client = new SshClient(conInfo))
{
ForwardedPortLocal port = new ForwardedPortLocal("127.0.0.1", 0, "127.0.0.1", 22);
client.Connect();
client.AddForwardedPort(port);
port.Start();
MySqlConnection conn = new MySqlConnection(connBuilder.ConnectionString);
conn.Open();
conn.ChangeDatabase(connBuilder.Database);
var command = "SELECT * FROM DatabaseName.Clients LIMIT 10";
using (MySqlCommand cmd = new MySqlCommand(command))
{
using (MySqlDataAdapter sda = new MySqlDataAdapter())
{
cmd.Connection = conn;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
下面的大部分代码都是不言自明的。我仍然提出了必要的评论。我能够使用下面的代码连接到 MySql 数据库。我使用过 SSH 库here https://sshnet.codeplex.com/releases/view/120565和用于 .NET 的 MySql 连接器。
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...");
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)