[英]Connecting Visual Studio to a SSH Tunneled MySQL Server
我正在尋找一種配置數據庫連接的解決方法。
我看到打開 3306 端口是危險的,我們應該使用 SSH 隧道來連接數據庫。
我使用 docker 配置了我的 MySQL 服務器,並使用 MySQL Workbench 成功連接了它
現在我必須配置它並將其連接到 Visual Studio 2022 才能查詢數據庫。
Visual Studio 2022 僅受 MySQL Data through NuGet 包的支持,這些包沒有 gui 連接設置。
我安裝了 MySQL 數據庫正式支持的 Visual Studio 2019,可以通過數據源進行配置。
如果配置了 SSH 隧道,我如何設置 MySQL 數據庫連接到我的 Visual Studio。
添加連接 window 只顯示連接的基本信息。 我不確定如何通過 SSH 隧道進行配置。
先感謝您。
出於安全考慮,有時數據庫服務器只能通過SSH訪問。比如MySql服務安裝在服務器A上,機器A只能被機器B訪問,部署環境可能在C機器上。在這個case, C 服務器通過B服務器連接到A服務器。 此時需要SSH連接,需要SSH.NET class庫:代碼如下:
using MySql.Data.MySqlClient;
using Renci.SshNet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SSHMySql
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
SSHConnectMySql();
}
public void SSHConnectMySql()
{
string SSHHost = "*.*.*.*"; // SSH address
int SSHPort = ; // SSH port
string SSHUser = "user"; // SSH username
string SSHPassword = "pwd"; // SSH password
string sqlIPA = "127.0.0.1";// Map addresses In fact, it is possible to write other MySql on Linux My.cnf bind-address can be set to 0.0.0.0 or not
string sqlHost = "192.168.1.20"; // The IP address of the machine installed by mysql can also be an intranet IP, for example: 192.168.1.20
uint sqlport = ; // Database port and mapping port
string sqlConn = "Database=mysql;Data Source=" + sqlIPA + ";Port=" + sqlport + ";User Id=user;Password=pwd;CharSet=utf8";
string sqlSELECT = "select * from user";
PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo(SSHHost, SSHPort, SSHUser, SSHPassword);
connectionInfo.Timeout = TimeSpan.FromSeconds();
using (var client = new SshClient(connectionInfo))
{
try
{
client.Connect();
if (!client.IsConnected)
{
MessageBox.Show("SSH connect failed");
}
var portFwdL = new ForwardedPortLocal(sqlIPA, sqlport, sqlHost, sqlport); // map to local port
client.AddForwardedPort(portFwdL);
portFwdL.Start();
if (!client.IsConnected)
{
MessageBox.Show("port forwarding failed");
}
MySqlConnection conn = new MySqlConnection(sqlConn);
MySqlDataAdapter myDataAdapter = new MySqlDataAdapter();
myDataAdapter.SelectCommand = new MySqlCommand(sqlSELECT, conn);
try
{
conn.Open();
DataSet ds = new DataSet();
myDataAdapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[];
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
finally
{
conn.Close();
}
client.Disconnect();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
}
注意:如果報錯,可以在本地(開發機)停止MySql服務。
所需 dll:SSHDLL.rar
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.