在Java中通过SSH连接SQL数据库

时间:2016-03-11 06:16:44

标签: java database ssh

为什么这段代码不起作用?与ssh的连接没关系,但是在服务器上找不到数据库...为什么???

public static void main(String[] args) throws SQLException {

    String host="ssh.example.com";
    String rhost="localhost";
    int rport=3306;
    int lport=4321;

    String user="example.com";
    String password="sshPass";

    String dbuserName = "example_com";
    String dbpassword = "dbPass";
    String url = "jdbc:mysql://localhost:3306/example_com";
    String driverName="com.mysql.jdbc.Driver";
    Session session= null;

    try{

        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");

        //mysql database connectivity                  
        Class.forName(driverName);
        dbConn  = DriverManager.getConnection (url, dbuserName, dbpassword);

        System.out.println ("Database connection established");
        System.out.println("DONE");

 String sql = "SELECT * FROM client ";

 PreparedStatement ps = dbConn.prepareStatement(sql);
 ResultSet rs = ps.executeQuery();
 while (rs.next()){
  System.out.println("*** "+rs.getString("name")+" ***");
 }


    }catch(JSchException | ClassNotFoundException | SQLException e){
        e.printStackTrace();            
    }finally{
        if(dbConn != null && !dbConn.isClosed()){
            System.out.println("Closing Database Connection");
            dbConn.close();
        }
        if(session !=null && session.isConnected()){
            System.out.println("Closing SSH Connection");
            session.disconnect();
        }
    }
}

}

它连接到主机但不连接到数据库。

Connected
localhost:4321 -> localhost:3306
Port Forwarded
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'example_com'

我在服务器上有example_com数据库。

0 个答案:

没有答案