gpt4 book ai didi

c# - 使用 SSH.NET 库从 .NET 连接到 MySQL

转载 作者:行者123 更新时间:2023-11-29 01:07:42 25 4
gpt4 key购买 nike

enter image description here

我正在开发一个网页 (ASP.NET/C#),它通过 SSH 查询远程服务器上的 (MySQL) 数据库。我正在使用这两个库 (mysql-connector-net-6.9.7) 和 (Renci.SshNet.dll)。

我可以通过 SSH 连接在远程服务器上使用 MySQL Workbench 访问 MySQL 数据库:
portal.RemoteServer.edu:22”使用“RemoteServerUsername”和
远程服务器密码”。

这是我的 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 数据库。我使用了来自 here 的 SSH 库和 .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...");
}
}

关于c# - 使用 SSH.NET 库从 .NET 连接到 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32603982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com