首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Java通过SSH连接到远程MySQL数据库

使用Java通过SSH连接到远程MySQL数据库
EN

Stack Overflow用户
提问于 2009-12-28 14:57:01
回答 6查看 75K关注 0票数 49

如何从java应用程序通过SSH连接到远程MySQL数据库?小的代码示例对我很有帮助,我会很感激的。

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2009-12-28 15:46:52

我的理解是,您希望通过SSH隧道访问运行在远程机器上并侦听端口3306的mysql服务器。

要使用命令行ssh客户端创建从本地计算机上的端口1234到远程计算机上的端口3306的隧道,您需要在本地计算机上键入以下命令:

代码语言:javascript
复制
ssh -L 1234:localhost:3306 mysql.server.remote

要在Java中做同样的事情,您可以使用SSH2的Java实现JSch。来自其网站:

JSch允许您连接到sshd服务器并使用端口转发、X11转发、文件传输等,并且您可以将其功能集成到您自己的Java程序中。JSch是在BSD样式许可下授权的。

举个例子,看看PortForwardingL.java。连接会话后,使用类似jdbc:mysql://localhost:1234/[database]的内容作为连接URL,创建到MySQL的JDBC连接。

票数 45
EN

Stack Overflow用户

发布于 2013-01-03 17:55:24

我的详细代码如下:

代码语言:javascript
复制
package mypackage;
import java.sql.*;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class UpdateMySqlDatabase {
    static int lport;
    static String rhost;
    static int rport;
    public static void go(){
        String user = "ripon";
        String password = "wasim";
        String host = "myhost.ripon.wasim";
        int port=22;
        try
            {
            JSch jsch = new JSch();
            Session session = jsch.getSession(user, host, port);
            lport = 4321;
            rhost = "localhost";
            rport = 3306;
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            System.out.println("Establishing Connection...");
            session.connect();
            int assinged_port=session.setPortForwardingL(lport, rhost, rport);
            System.out.println("localhost:"+assinged_port+" -> "+rhost+":"+rport);
            }
        catch(Exception e){System.err.print(e);}
    }
    public static void main(String[] args) {
        try{
            go();
        } catch(Exception ex){
            ex.printStackTrace();
        }
          System.out.println("An example for updating a Row from Mysql Database!");
          Connection con = null;
          String driver = "com.mysql.jdbc.Driver";
          String url = "jdbc:mysql://" + rhost +":" + lport + "/";
          String db = "testDB";
          String dbUser = "wasim";
          String dbPasswd = "riponalwasim123";
          try{
          Class.forName(driver);
          con = DriverManager.getConnection(url+db, dbUser, dbPasswd);
          try{
          Statement st = con.createStatement();
          String sql = "UPDATE MyTableName " +
                  "SET email = 'ripon.wasim@smile.com' WHERE email='peace@happy.com'";

          int update = st.executeUpdate(sql);
          if(update >= 1){
          System.out.println("Row is updated.");
          }
          else{
          System.out.println("Row is not updated.");
          }
          }
          catch (SQLException s){
          System.out.println("SQL statement is not executed!");
          }
          }
          catch (Exception e){
          e.printStackTrace();
          }
          }
        }
票数 18
EN

Stack Overflow用户

发布于 2019-04-18 18:55:39

虽然现有的答案是正确的,但它们在其他代码的膨胀中掩盖了重要的代码。

以下是通过SSH通道建立JDBC (或任何其他)数据库连接所需的基本代码:

代码语言:javascript
复制
String jumpserverHost = "ssh.example.com";
String jumpserverUsername = "sshuser";
// The hostname/IP address and port, you would use on the SSH server
// to connect to the database.
// If the database runs on the same machine as the SSH server, use "localhost".
String databaseHost = "database.example.com";
int databasePort = 3306;
String databaseUsername = "dbuser";
String databasePassword = "dbpass";

JSch jsch = new JSch();
// Public key authentication example
// (but you can use password authentication, if appropriate).
jsch.addIdentity("~/.ssh/id_rsa");

// Connect to SSH jump server (this does not show an authentication code)
Session session = jsch.getSession(jumpserverUsername, jumpserverHost);
session.connect();

// Forward randomly chosen local port through the SSH channel to database host/port
int forwardedPort = session.setPortForwardingL(0, databaseHost, databasePort);

// Connect to the forwarded port (the local end of the SSH tunnel)
// If you don't use JDBC, but another database client,
// just connect it to the localhost:forwardedPort
String url = "jdbc:mysql://localhost:" + forwardedPort;
Connection con =
    DriverManager.getConnection(url, databaseUsername, databasePassword);

您还必须处理主机密钥验证。有关这一点,请参阅:

票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1968293

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档