Connect to the database using jsch
Connect to a remote database through java's jsch
Sometimes our local code may not be able to connect to the database, because the database added a whitelist, specified ip server can connect to the database, but we can connect to the specified ip server, and then connect to the database through the server, just like many database visualization software. By using jsch, we can also do this at the code level. Don't say much, just open the code:
JSch jsch = new JSch (); Session sess; / / where xxx.xxx.xxx.xxx is the whitelisted remote server sess = jsch.getSession ("ubuntu", "xxx.xxx.xxx.xxx", 22); sess.setPassword ("*"); sess.setConfig ("StrictHostKeyChecking", "no"); sess.connect () / / here xxx.xxx.xxx.xxx is the database connection address / / through this set method, the remote port 3306 can be designated as the local port 3308. Since the author has used 3306 locally, it is designated as port 3308 sess.setPortForwardingL (3308, "xxx.xxx.xxx.xxx", 3306). Try {/ / reads the configuration file. Note that the database address in the configuration file is localhost, and the port is 3308 reader = Resources.getResourceAsReader ("conf.xml") that you just specified;} catch (IOException e) {e.printStackTrace ();} sqlSessionFactory = new SqlSessionFactoryBuilder (). Build (reader); SqlSession session = sqlSessionFactory.openSession () String statement = "com.saishangmingzhu.getData"; / / Mapping the identity string List ll=session.selectList (statement) of sql; System.out.println (ll); session.commit (); session.close (); sess.disconnect ()
Of course, the use of jsch to achieve ssh connection is not limited to database connection, but you can also operate on the server on the ssh connection, such as executing shell and other related commands, and record it later.