Connecting to a remote database via Java Jsch
Sometimes our local code may not be able to connect to the database, because the database has added a whitelist, the IP server can connect to the database, but we can connect to the designated IP server, and then through the server to connect to the database, like many database visualization software. By using Jsch, we can also implement this functionality at the code level. Words do not say, directly open code:
jsch jsch = new jsch ();
Session sess; //here xxx.xxx.xxx.xxx for 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 for database connection address //This set method allows the remote port 3306 to be designated as the local 3308 port, because the author local 3306 has been used, it is designated as 3308 Port
sess.setportforwardingl (3308, "xxx.xxx.xxx.xxx", 3306); try { //read the configuration file, it is important to note that the database address in this configuration file is localhost, the port is the 3308 that was just specified
reader = resources.getresourceasreader ("Conf.xml"); } catch (ioexception e) {
e.printstacktrace (); }
Sqlsessionfactory = new sqlsessionfactorybuilder (). build (reader); SqlSession session =
Sqlsessionfactory.opensession (); String statement = "Com.saishangmingzhu.getData
";//mapping SQL identification string list ll=session.selectlist (statement);
system.out.println (LL); session.commit ();
session.close (); sess.disconnect ();
Of course, the use of Jsch to implement SSH connection is not limited to the implementation of the database connection, but also the SSH connection on the server to operate, such as the execution of shell and other related commands, follow-up record it
This article is from the "Stuffed Pig" blog, please be sure to keep this source http://zuohao1990.blog.51cto.com/6057850/1907153
Connect to a database using Jsch