NutzCN Logo
问答 jsch+jdbc实现ssh通道查询数据
发布于 2213天前 作者 qq_e1b46c93 1949 次浏览 复制 上一个帖子 下一个帖子
标签:
int lport = 5656;
        String rhost = "xxx.aliyuncs.com";
        String host = "192.168.1.23";
        int rport = 3306;
        String user = "root";
        String password = "123456";
        String dbuserName = "root";
        String dbpassword = "123456";
        String url = "jdbc:mysql://localhost:" + lport + "/qzbk";
        String driverName = "com.mysql.jdbc.Driver";
        Connection conn = null;
        Session session = null;

        //Set StrictHostKeyChecking property to no to avoid UnknownHostKey issue
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        JSch jsch = new JSch();
        session = jsch.getSession(user, host, 22);
        session.setPassword(password);
        session.setConfig(config);
        session.connect();
        System.out.println("Connected");
        int assinged_port = session.setPortForwardingL(lport, rhost, rport);
        System.out.println("localhost:" + assinged_port + " -> " + rhost + ":" + rport);
        System.out.println("Port Forwarded");


        Dao dao =new NutDao();
        //dao.



        //mysql database connectivity
        Class.forName(driverName).newInstance();
        conn = DriverManager.getConnection(url, dbuserName, dbpassword);
        System.out.println("Database connection established");
        System.out.println("DONE");




        if (conn != null && !conn.isClosed()) {
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("select count(0) from user_info");
            while (rs.next()) {
                int a = rs.getInt(1);
                System.out.println(a);
            }
            System.out.println("Closing Database Connection");
            conn.close();
        }
        if (session != null && session.isConnected()) {
            System.out.println("Closing SSH Connection");
            session.disconnect();
        }
5 回复

哦, 先建隧道, 再建连接

是nutz还是nutzboot呢? 虽然解法类似

dao.js里面去掉dataSource的声明,然后写个类

@IocBean
public class MyBeans {
     @Inject PropertiesProxy conf;
     @IocBean(name="dataSource", depose="close")
     public DataSource createRemoteDataSource() {
              // xxx 建立隧道xxxx 你会写的啦
              
              // 返回个数据源给NutDao用
              SimpleDataSource dataSource = ... ; // 设置一下参数
              return dataSource;
              // return conf.make(DruidDataSource.class, "db."); // 或者用连接池
      }
}

可以了,非常感谢

添加回复
请先登陆
回到顶部