Java SSH 登錄 MySQL 數據庫
在實際的開發中,我們往往需要通過Java程序連接MySQL數據庫并進行一些操作。而有些情況下我們的MySQL服務器可能在一臺不能直接訪問的遠程機器上,這時候我們需要通過SSH協議進行安全連接,再進行數據庫操作。下面我們就講解一下如何使用Java SSH登錄MySQL數據庫。
// 導入相關包 import java.sql.*; import com.jcraft.jsch.*; public class SSHMySQL { // SSH連接信息 private static String sshHost = "sshHost"; private static String sshUser = "sshUser"; private static String sshPassword = "sshPassword"; // MySQL連接信息 private static String mysqlHost = "mysqlHost"; private static String mysqlDB = "mysqlDB"; private static String mysqlUser = "mysqlUser"; private static String mysqlPassword = "mysqlPassword"; private static int sshPort = 22; private static int mysqlPort = 3306; // SSH登錄并打開MySQL端口 public void sshConnect() { try { JSch jsch = new JSch(); Session session = jsch.getSession(sshUser, sshHost, sshPort); session.setPassword(sshPassword); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); System.out.println("SSH Connected"); int assignedPort = session.setPortForwardingL(0, mysqlHost, mysqlPort); System.out.println("MySQL Port Forwarded"); mysqlConnect("127.0.0.1", assignedPort, mysqlDB, mysqlUser, mysqlPassword); } catch (Exception e) { e.printStackTrace(); } } // MySQL登錄 public static void mysqlConnect(String host, int port, String dbName, String user, String password) { try { Class.forName("com.mysql.cj.jdbc.Driver"); String url = "jdbc:mysql://" + host + ":" + port + "/" + dbName + "?useSSL=false&serverTimezone=UTC"; Connection conn = DriverManager.getConnection(url, user, password); System.out.println("MySQL Connected"); Statement stmt = conn.createStatement(); String query = "SELECT * FROM tablename"; ResultSet rs = stmt.executeQuery(query); while(rs.next()) { System.out.println(rs.getString("columnname")); } } catch (Exception e) { e.printStackTrace(); } } // 主函數 public static void main(String[] args) { SSHMySQL sshmysql = new SSHMySQL(); sshmysql.sshConnect(); } }
以上代碼中,我們使用JSch包連接SSH服務器,并通過setPortForwardingL方法打開MySQL的端口進行連接。接著我們使用JDBC的方式連接MySQL,通過執行相關SQL語句來操作MySQL數據庫。