原文地址: https://blog.csdn.net/earbao/article/details/50216999,session.setPortForwardingL稍有改动
- import com.jcraft.jsch.JSch;
- import com.jcraft.jsch.Session;
- import java.sql.*;
- //http://my.oschina.net/Thinkeryjgfn/blog/177283
- //http://www.cnblogs.com/I-will-be-different/p/3925351.html?utm_source=tuicool&utm_medium=referral
- //java jdbc使用SSH隧道连接mysql数据库demo
- public class ChangeDB {
- public static void go() {
- try {
- JSch jsch = new JSch();
- Session session = jsch.getSession("yunshouhu", "192.168.0.102", 22);
- session.setPassword("xxxx");
- session.setConfig("StrictHostKeyChecking", "no");
- session.connect();
- System.out.println(session.getServerVersion());//这里打印SSH服务器版本信息
- //ssh -L 192.168.0.102:5555:192.168.0.101:3306 yunshouhu@192.168.0.102 正向代理
- int assinged_port = session.setPortForwardingL((3306, mysqlurl, 3306);//端口映射 转发 数据库服务器地址url
- System.out.println("localhost:" + assinged_port);
- //ssh -R 192.168.0.102:5555:192.168.0.101:3306 yunshouhu@192.168.0.102
- //session.setPortForwardingR("192.168.0.102",5555, "192.168.0.101", 3306);
- // System.out.println("localhost: -> ");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public static void main(String[] args) {
- try {
- //1、加载驱动
- Class.forName("com.mysql.jdbc.Driver");
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- }
- //2、创建连接
- Connection conn = null;
- Connection conn2 = null;
- try {
- conn2 = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "hadoop", "xxxx");
- getData(conn2);
- } catch (SQLException e) {
- System.out.println("未连接上数据库");
- e.printStackTrace();
- }
- try{
- System.out.println("=============");
- go();
- conn = DriverManager.getConnection("jdbc:mysql://192.168.0.101:5555/mysql", "hadoop", "xxx");
- getData(conn);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- private static void getData(Connection conn) throws SQLException {
- // 获取所有表名
- Statement statement = conn.createStatement();
- ResultSet resultSet = statement
- .executeQuery("select * from help_keyword");
- // 获取列名
- ResultSetMetaData metaData = resultSet.getMetaData();
- for (int i = 0; i < metaData.getColumnCount(); i++) {
- // resultSet数据下标从1开始
- String columnName = metaData.getColumnName(i + 1);
- int type = metaData.getColumnType(i + 1);
- if (Types.INTEGER == type) {
- // int
- } else if (Types.VARCHAR == type) {
- // String
- }
- System.out.print(columnName + "\t");
- }
- System.out.println();
- // 获取数据
- while (resultSet.next()) {
- for (int i = 0; i < metaData.getColumnCount(); i++) {
- // resultSet数据下标从1开始
- System.out.print(resultSet.getString(i + 1) + "\t");
- }
- System.out.println();
- }
- statement.close();
- conn.close();
- }
- }