Connect to remote MySQL database through SSH using Java - java

How can I connect to remote MySQL database through SSH from java application? Small code example is helpful for me and I'd appreciate this.

My understanding is that you want to access a mysql server running on a remote machine and listening on let's say port 3306 through a SSH tunnel.
To create such a tunnel from port 1234 on your local machine to port 3306 on a remote machine using the command line ssh client, you would type the following command from your local machine:
ssh -L 1234:localhost:3306 mysql.server.remote
To do the same thing from Java, you could use JSch, a Java implementation of SSH2. From its website:
JSch allows you to connect to an sshd server and use port forwarding, X11 forwarding, file transfer, etc., and you can integrate its functionality into your own Java programs. JSch is licensed under BSD style license.
For an example, have a look at PortForwardingL.java. Once the session connected, create your JDBC connection to MySQL using something like jdbc:mysql://localhost:1234/[database] as connection URL.

My detail code is below:
package mypackage;
import java.sql.*;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class UpdateMySqlDatabase {
static int lport;
static String rhost;
static int rport;
public static void go(){
String user = "ripon";
String password = "wasim";
String host = "myhost.ripon.wasim";
int port=22;
try
{
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
lport = 4321;
rhost = "localhost";
rport = 3306;
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
session.connect();
int assinged_port=session.setPortForwardingL(lport, rhost, rport);
System.out.println("localhost:"+assinged_port+" -> "+rhost+":"+rport);
}
catch(Exception e){System.err.print(e);}
}
public static void main(String[] args) {
try{
go();
} catch(Exception ex){
ex.printStackTrace();
}
System.out.println("An example for updating a Row from Mysql Database!");
Connection con = null;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://" + rhost +":" + lport + "/";
String db = "testDB";
String dbUser = "wasim";
String dbPasswd = "riponalwasim123";
try{
Class.forName(driver);
con = DriverManager.getConnection(url+db, dbUser, dbPasswd);
try{
Statement st = con.createStatement();
String sql = "UPDATE MyTableName " +
"SET email = 'ripon.wasim#smile.com' WHERE email='peace#happy.com'";
int update = st.executeUpdate(sql);
if(update >= 1){
System.out.println("Row is updated.");
}
else{
System.out.println("Row is not updated.");
}
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}

While the existing answers are correct, they obscure the significant code in bloats of other code.
This is the basic code you need to tunnel your JDBC (or any other) database connection through an SSH channel:
String jumpserverHost = "ssh.example.com";
String jumpserverUsername = "sshuser";
// The hostname/IP address and port, you would use on the SSH server
// to connect to the database.
// If the database runs on the same machine as the SSH server, use "localhost".
String databaseHost = "database.example.com";
int databasePort = 3306;
String databaseUsername = "dbuser";
String databasePassword = "dbpass";
JSch jsch = new JSch();
// Public key authentication example
// (but you can use password authentication, if appropriate).
jsch.addIdentity("~/.ssh/id_rsa");
// Connect to SSH jump server (this does not show an authentication code)
Session session = jsch.getSession(jumpserverUsername, jumpserverHost);
session.connect();
// Forward randomly chosen local port through the SSH channel to database host/port
int forwardedPort = session.setPortForwardingL(0, databaseHost, databasePort);
// Connect to the forwarded port (the local end of the SSH tunnel)
// If you don't use JDBC, but another database client,
// just connect it to the localhost:forwardedPort
String url = "jdbc:mysql://localhost:" + forwardedPort;
Connection con =
DriverManager.getConnection(url, databaseUsername, databasePassword);
You will also have to deal with host key verification. For that see:
How to resolve Java UnknownHostKey, while using JSch SFTP library?

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
public class CTestDriver {
private static void doSshTunnel(String strSshUser, String strSshPassword, String strSshHost, int nSshPort,
String strRemoteHost, int nLocalPort, int nRemotePort) throws JSchException {
final JSch jsch = new JSch();
Session session = jsch.getSession(strSshUser, strSshHost, 22);
session.setPassword(strSshPassword);
final Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
session.setPortForwardingL(nLocalPort, strRemoteHost, nRemotePort);
}
public static void main(String[] args) {
try {
String strSshUser = "ssh_user_name"; // SSH loging username
String strSshPassword = "abcd1234"; // SSH login password
String strSshHost = "your.ssh.hostname.com"; // hostname or ip or
// SSH server
int nSshPort = 22; // remote SSH host port number
String strRemoteHost = "your.database.hostname.com"; // hostname or
// ip of
// your
// database
// server
int nLocalPort = 3366; // local port number use to bind SSH tunnel
int nRemotePort = 3306; // remote port number of your database
String strDbUser = "db_user_name"; // database loging username
String strDbPassword = "4321dcba"; // database login password
CTestDriver.doSshTunnel(strSshUser, strSshPassword, strSshHost, nSshPort, strRemoteHost, nLocalPort,
nRemotePort);
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:" + nLocalPort, strDbUser,
strDbPassword);
con.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.exit(0);
}
}
}

package framework.restapi.utils;
import java.sql.*;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
public class SQLConnection {
private static Connection connection = null;
private static Session session = null;
private static void connectToServer(String dataBaseName) throws SQLException {
connectSSH();
connectToDataBase(dataBaseName);
}
private static void connectSSH() throws SQLException {
String sshHost = "";
String sshuser = "";
String dbuserName = "";
String dbpassword = "";
String SshKeyFilepath = "/Users/XXXXXX/.ssh/id_rsa";
int localPort = 8740; // any free port can be used
String remoteHost = "127.0.0.1";
int remotePort = 3306;
String localSSHUrl = "localhost";
/***************/
String driverName = "com.mysql.jdbc.Driver";
try {
java.util.Properties config = new java.util.Properties();
JSch jsch = new JSch();
session = jsch.getSession(sshuser, sshHost, 22);
jsch.addIdentity(SshKeyFilepath);
config.put("StrictHostKeyChecking", "no");
config.put("ConnectionAttempts", "3");
session.setConfig(config);
session.connect();
System.out.println("SSH Connected");
Class.forName(driverName).newInstance();
int assinged_port = session.setPortForwardingL(localPort, remoteHost, remotePort);
System.out.println("localhost:" + assinged_port + " -> " + remoteHost + ":" + remotePort);
System.out.println("Port Forwarded");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void connectToDataBase(String dataBaseName) throws SQLException {
String dbuserName = "sf2_showpad_biz";
String dbpassword = "lOAWEnL3K";
int localPort = 8740; // any free port can be used
String localSSHUrl = "localhost";
try {
//mysql database connectivity
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setServerName(localSSHUrl);
dataSource.setPortNumber(localPort);
dataSource.setUser(dbuserName);
dataSource.setAllowMultiQueries(true);
dataSource.setPassword(dbpassword);
dataSource.setDatabaseName(dataBaseName);
connection = dataSource.getConnection();
System.out.print("Connection to server successful!:" + connection + "\n\n");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void closeConnections() {
CloseDataBaseConnection();
CloseSSHConnection();
}
private static void CloseDataBaseConnection() {
try {
if (connection != null && !connection.isClosed()) {
System.out.println("Closing Database Connection");
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private static void CloseSSHConnection() {
if (session != null && session.isConnected()) {
System.out.println("Closing SSH Connection");
session.disconnect();
}
}
// works ONLY FOR single query (one SELECT or one DELETE etc)
private static ResultSet executeMyQuery(String query, String dataBaseName) {
ResultSet resultSet = null;
try {
connectToServer(dataBaseName);
Statement stmt = connection.createStatement();
resultSet = stmt.executeQuery(query);
System.out.println("Database connection success");
} catch (SQLException e) {
e.printStackTrace();
}
return resultSet;
}
public static void DeleteOrganisationReferencesFromDB(String organisationsLike) {
try {
connectToServer("ServerName");
Statement stmt = connection.createStatement();
ResultSet resultSet = stmt.executeQuery("select * from DB1");
String organisationsToDelete = "";
List<String> organisationsIds = new ArrayList<String>();
// create string with id`s values to delete organisations references
while (resultSet.next()) {
String actualValue = resultSet.getString("id");
organisationsIds.add(actualValue);
}
for (int i = 0; i < organisationsIds.size(); i++) {
organisationsToDelete = " " + organisationsToDelete + organisationsIds.get(i);
if (i != organisationsIds.size() - 1) {
organisationsToDelete = organisationsToDelete + ", ";
}
}
stmt.executeUpdate(" DELETE FROM `DB1`.`table1` WHERE `DB1`.`table1`.`organisation_id` in ( " + organisationsToDelete + " );");
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeConnections();
}
}
public static List<String> getOrganisationsDBNamesBySubdomain(String organisationsLike) {
List<String> organisationDbNames = new ArrayList<String>();
ResultSet resultSet = executeMyQuery("select `DB`.organisation.dbname from `DB1`.organisation where subdomain like '" + organisationsLike + "%'", "DB1");
try {
while (resultSet.next()) {
String actualValue = resultSet.getString("dbname");
organisationDbNames.add(actualValue);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeConnections();
}
return organisationDbNames;
}
public static List<String> getAllDBNames() {
// get all live db names incentral DB
List<String> organisationDbNames = new ArrayList<String>();
ResultSet resultSet = executeMyQuery("show databases", "DB1");
try {
while (resultSet.next()) {
String actualValue = resultSet.getString("Database");
organisationDbNames.add(actualValue);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeConnections();
}
return organisationDbNames;
}
public static void deleteDataBasesByName(List<String> DataBasesNamesList) {
try {
connectSSH();
int dataBasesAmount = DataBasesNamesList.size();
for (int i = 0; i < dataBasesAmount; i++) {
connectToDataBase(DataBasesNamesList.get(i));
Statement stmt = connection.createStatement();
stmt.executeUpdate("DROP database `" + DataBasesNamesList.get(i) + "`");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
CloseDataBaseConnection();
closeConnections();
}
}
}

First of all, thank you works great!
Though, I wonder if I should reuse that Session for every (potentially simultaneous) SQL Connection, or if I should create a new Session every time and only refresh it if for some reason it has expired.
Currently, I would every time I make a connection make a new instance of that Controller here and then do the SQL queries with the connection I got from it, then close it manually.
Would also be nice if I could make the class useable with try-with-resource and it closing itself. Will look into that. Cause I don´t wanna miss closing it.
That´s how the thing looks like, I'm getting DB Connections from right now.
public class ConnectionManager {
private Connection con = null;
private Session session = null;
public Connection getConnection() {
Connection con = null;
var settings = new DbSettingsController();
boolean useSSH = settings.getSetting(SettingKey.UseSSH).equals("true");
String sshPort = settings.getSetting(SettingKey.SSHPort);
String sqlIp = settings.getSetting(SettingKey.MySqlIP);
String sqlPort = settings.getSetting(SettingKey.MySqlPort);
if(useSSH) {
JSch jSch = new JSch();
try {
this.session = jSch.getSession(settings.getSetting(SettingKey.SSHUser),
settings.getSetting(SettingKey.SSHHost),
Integer.valueOf(sshPort));
this.session.setPassword(settings.getSetting(SettingKey.SSHPassword));
this.session.setConfig("StrictHostKeyChecking", "no");
this.session.connect();
this.session.setPortForwardingL(Integer.parseInt(sshPort), sqlIp, Integer.parseInt(sqlPort));
} catch (JSchException e) {
e.printStackTrace();
}
}
var connectionString = String.format("jdbc:mysql://%s:%s/%s?autoReconnect=true&useSSL=false",
sqlIp, useSSH ? sshPort : sqlPort,
settings.getSetting(SettingKey.MySqlShema));
var user = settings.getSetting(SettingKey.MySqlUser);
var password = settings.getSetting(SettingKey.MySqlPassword);
try {
con = DriverManager.getConnection(connectionString, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
public void close() {
if(this.con != null) {
try {
this.con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(this.session != null) {
this.session.disconnect();
}
}
If you wonder DbSettingsController I´ve made myself too, just puts settings in a Text column in a local SQLite DB, with a key assigned to it (that enum´s int value). Was just copy paste code I reused from some other project, so it was simple and fast to just do that this way.

Related

Hive is not getting connected after getting connected to ec2-linux instance [duplicate]

How can I connect to remote MySQL database through SSH from java application? Small code example is helpful for me and I'd appreciate this.
My understanding is that you want to access a mysql server running on a remote machine and listening on let's say port 3306 through a SSH tunnel.
To create such a tunnel from port 1234 on your local machine to port 3306 on a remote machine using the command line ssh client, you would type the following command from your local machine:
ssh -L 1234:localhost:3306 mysql.server.remote
To do the same thing from Java, you could use JSch, a Java implementation of SSH2. From its website:
JSch allows you to connect to an sshd server and use port forwarding, X11 forwarding, file transfer, etc., and you can integrate its functionality into your own Java programs. JSch is licensed under BSD style license.
For an example, have a look at PortForwardingL.java. Once the session connected, create your JDBC connection to MySQL using something like jdbc:mysql://localhost:1234/[database] as connection URL.
My detail code is below:
package mypackage;
import java.sql.*;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class UpdateMySqlDatabase {
static int lport;
static String rhost;
static int rport;
public static void go(){
String user = "ripon";
String password = "wasim";
String host = "myhost.ripon.wasim";
int port=22;
try
{
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
lport = 4321;
rhost = "localhost";
rport = 3306;
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
session.connect();
int assinged_port=session.setPortForwardingL(lport, rhost, rport);
System.out.println("localhost:"+assinged_port+" -> "+rhost+":"+rport);
}
catch(Exception e){System.err.print(e);}
}
public static void main(String[] args) {
try{
go();
} catch(Exception ex){
ex.printStackTrace();
}
System.out.println("An example for updating a Row from Mysql Database!");
Connection con = null;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://" + rhost +":" + lport + "/";
String db = "testDB";
String dbUser = "wasim";
String dbPasswd = "riponalwasim123";
try{
Class.forName(driver);
con = DriverManager.getConnection(url+db, dbUser, dbPasswd);
try{
Statement st = con.createStatement();
String sql = "UPDATE MyTableName " +
"SET email = 'ripon.wasim#smile.com' WHERE email='peace#happy.com'";
int update = st.executeUpdate(sql);
if(update >= 1){
System.out.println("Row is updated.");
}
else{
System.out.println("Row is not updated.");
}
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
While the existing answers are correct, they obscure the significant code in bloats of other code.
This is the basic code you need to tunnel your JDBC (or any other) database connection through an SSH channel:
String jumpserverHost = "ssh.example.com";
String jumpserverUsername = "sshuser";
// The hostname/IP address and port, you would use on the SSH server
// to connect to the database.
// If the database runs on the same machine as the SSH server, use "localhost".
String databaseHost = "database.example.com";
int databasePort = 3306;
String databaseUsername = "dbuser";
String databasePassword = "dbpass";
JSch jsch = new JSch();
// Public key authentication example
// (but you can use password authentication, if appropriate).
jsch.addIdentity("~/.ssh/id_rsa");
// Connect to SSH jump server (this does not show an authentication code)
Session session = jsch.getSession(jumpserverUsername, jumpserverHost);
session.connect();
// Forward randomly chosen local port through the SSH channel to database host/port
int forwardedPort = session.setPortForwardingL(0, databaseHost, databasePort);
// Connect to the forwarded port (the local end of the SSH tunnel)
// If you don't use JDBC, but another database client,
// just connect it to the localhost:forwardedPort
String url = "jdbc:mysql://localhost:" + forwardedPort;
Connection con =
DriverManager.getConnection(url, databaseUsername, databasePassword);
You will also have to deal with host key verification. For that see:
How to resolve Java UnknownHostKey, while using JSch SFTP library?
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
public class CTestDriver {
private static void doSshTunnel(String strSshUser, String strSshPassword, String strSshHost, int nSshPort,
String strRemoteHost, int nLocalPort, int nRemotePort) throws JSchException {
final JSch jsch = new JSch();
Session session = jsch.getSession(strSshUser, strSshHost, 22);
session.setPassword(strSshPassword);
final Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
session.setPortForwardingL(nLocalPort, strRemoteHost, nRemotePort);
}
public static void main(String[] args) {
try {
String strSshUser = "ssh_user_name"; // SSH loging username
String strSshPassword = "abcd1234"; // SSH login password
String strSshHost = "your.ssh.hostname.com"; // hostname or ip or
// SSH server
int nSshPort = 22; // remote SSH host port number
String strRemoteHost = "your.database.hostname.com"; // hostname or
// ip of
// your
// database
// server
int nLocalPort = 3366; // local port number use to bind SSH tunnel
int nRemotePort = 3306; // remote port number of your database
String strDbUser = "db_user_name"; // database loging username
String strDbPassword = "4321dcba"; // database login password
CTestDriver.doSshTunnel(strSshUser, strSshPassword, strSshHost, nSshPort, strRemoteHost, nLocalPort,
nRemotePort);
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:" + nLocalPort, strDbUser,
strDbPassword);
con.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.exit(0);
}
}
}
package framework.restapi.utils;
import java.sql.*;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
public class SQLConnection {
private static Connection connection = null;
private static Session session = null;
private static void connectToServer(String dataBaseName) throws SQLException {
connectSSH();
connectToDataBase(dataBaseName);
}
private static void connectSSH() throws SQLException {
String sshHost = "";
String sshuser = "";
String dbuserName = "";
String dbpassword = "";
String SshKeyFilepath = "/Users/XXXXXX/.ssh/id_rsa";
int localPort = 8740; // any free port can be used
String remoteHost = "127.0.0.1";
int remotePort = 3306;
String localSSHUrl = "localhost";
/***************/
String driverName = "com.mysql.jdbc.Driver";
try {
java.util.Properties config = new java.util.Properties();
JSch jsch = new JSch();
session = jsch.getSession(sshuser, sshHost, 22);
jsch.addIdentity(SshKeyFilepath);
config.put("StrictHostKeyChecking", "no");
config.put("ConnectionAttempts", "3");
session.setConfig(config);
session.connect();
System.out.println("SSH Connected");
Class.forName(driverName).newInstance();
int assinged_port = session.setPortForwardingL(localPort, remoteHost, remotePort);
System.out.println("localhost:" + assinged_port + " -> " + remoteHost + ":" + remotePort);
System.out.println("Port Forwarded");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void connectToDataBase(String dataBaseName) throws SQLException {
String dbuserName = "sf2_showpad_biz";
String dbpassword = "lOAWEnL3K";
int localPort = 8740; // any free port can be used
String localSSHUrl = "localhost";
try {
//mysql database connectivity
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setServerName(localSSHUrl);
dataSource.setPortNumber(localPort);
dataSource.setUser(dbuserName);
dataSource.setAllowMultiQueries(true);
dataSource.setPassword(dbpassword);
dataSource.setDatabaseName(dataBaseName);
connection = dataSource.getConnection();
System.out.print("Connection to server successful!:" + connection + "\n\n");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void closeConnections() {
CloseDataBaseConnection();
CloseSSHConnection();
}
private static void CloseDataBaseConnection() {
try {
if (connection != null && !connection.isClosed()) {
System.out.println("Closing Database Connection");
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private static void CloseSSHConnection() {
if (session != null && session.isConnected()) {
System.out.println("Closing SSH Connection");
session.disconnect();
}
}
// works ONLY FOR single query (one SELECT or one DELETE etc)
private static ResultSet executeMyQuery(String query, String dataBaseName) {
ResultSet resultSet = null;
try {
connectToServer(dataBaseName);
Statement stmt = connection.createStatement();
resultSet = stmt.executeQuery(query);
System.out.println("Database connection success");
} catch (SQLException e) {
e.printStackTrace();
}
return resultSet;
}
public static void DeleteOrganisationReferencesFromDB(String organisationsLike) {
try {
connectToServer("ServerName");
Statement stmt = connection.createStatement();
ResultSet resultSet = stmt.executeQuery("select * from DB1");
String organisationsToDelete = "";
List<String> organisationsIds = new ArrayList<String>();
// create string with id`s values to delete organisations references
while (resultSet.next()) {
String actualValue = resultSet.getString("id");
organisationsIds.add(actualValue);
}
for (int i = 0; i < organisationsIds.size(); i++) {
organisationsToDelete = " " + organisationsToDelete + organisationsIds.get(i);
if (i != organisationsIds.size() - 1) {
organisationsToDelete = organisationsToDelete + ", ";
}
}
stmt.executeUpdate(" DELETE FROM `DB1`.`table1` WHERE `DB1`.`table1`.`organisation_id` in ( " + organisationsToDelete + " );");
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeConnections();
}
}
public static List<String> getOrganisationsDBNamesBySubdomain(String organisationsLike) {
List<String> organisationDbNames = new ArrayList<String>();
ResultSet resultSet = executeMyQuery("select `DB`.organisation.dbname from `DB1`.organisation where subdomain like '" + organisationsLike + "%'", "DB1");
try {
while (resultSet.next()) {
String actualValue = resultSet.getString("dbname");
organisationDbNames.add(actualValue);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeConnections();
}
return organisationDbNames;
}
public static List<String> getAllDBNames() {
// get all live db names incentral DB
List<String> organisationDbNames = new ArrayList<String>();
ResultSet resultSet = executeMyQuery("show databases", "DB1");
try {
while (resultSet.next()) {
String actualValue = resultSet.getString("Database");
organisationDbNames.add(actualValue);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeConnections();
}
return organisationDbNames;
}
public static void deleteDataBasesByName(List<String> DataBasesNamesList) {
try {
connectSSH();
int dataBasesAmount = DataBasesNamesList.size();
for (int i = 0; i < dataBasesAmount; i++) {
connectToDataBase(DataBasesNamesList.get(i));
Statement stmt = connection.createStatement();
stmt.executeUpdate("DROP database `" + DataBasesNamesList.get(i) + "`");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
CloseDataBaseConnection();
closeConnections();
}
}
}
First of all, thank you works great!
Though, I wonder if I should reuse that Session for every (potentially simultaneous) SQL Connection, or if I should create a new Session every time and only refresh it if for some reason it has expired.
Currently, I would every time I make a connection make a new instance of that Controller here and then do the SQL queries with the connection I got from it, then close it manually.
Would also be nice if I could make the class useable with try-with-resource and it closing itself. Will look into that. Cause I don´t wanna miss closing it.
That´s how the thing looks like, I'm getting DB Connections from right now.
public class ConnectionManager {
private Connection con = null;
private Session session = null;
public Connection getConnection() {
Connection con = null;
var settings = new DbSettingsController();
boolean useSSH = settings.getSetting(SettingKey.UseSSH).equals("true");
String sshPort = settings.getSetting(SettingKey.SSHPort);
String sqlIp = settings.getSetting(SettingKey.MySqlIP);
String sqlPort = settings.getSetting(SettingKey.MySqlPort);
if(useSSH) {
JSch jSch = new JSch();
try {
this.session = jSch.getSession(settings.getSetting(SettingKey.SSHUser),
settings.getSetting(SettingKey.SSHHost),
Integer.valueOf(sshPort));
this.session.setPassword(settings.getSetting(SettingKey.SSHPassword));
this.session.setConfig("StrictHostKeyChecking", "no");
this.session.connect();
this.session.setPortForwardingL(Integer.parseInt(sshPort), sqlIp, Integer.parseInt(sqlPort));
} catch (JSchException e) {
e.printStackTrace();
}
}
var connectionString = String.format("jdbc:mysql://%s:%s/%s?autoReconnect=true&useSSL=false",
sqlIp, useSSH ? sshPort : sqlPort,
settings.getSetting(SettingKey.MySqlShema));
var user = settings.getSetting(SettingKey.MySqlUser);
var password = settings.getSetting(SettingKey.MySqlPassword);
try {
con = DriverManager.getConnection(connectionString, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
public void close() {
if(this.con != null) {
try {
this.con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(this.session != null) {
this.session.disconnect();
}
}
If you wonder DbSettingsController I´ve made myself too, just puts settings in a Text column in a local SQLite DB, with a key assigned to it (that enum´s int value). Was just copy paste code I reused from some other project, so it was simple and fast to just do that this way.

selenium java try to access database through vpn

I try to verify total comment between frontend and database result. since the database can only accessed through VPN, it makes me stuck. I been tried with below code, but the result is empty, the only ssh connected in the console
public class ConnectDB {
private static Connection connection = null;
private static Session session = null;
private static void connectToServer(String dataBaseName) throws SQLException {
connectSSH();
connectToDataBase(dataBaseName);
}
public static void connectSSH() throws SQLException {
String sshHost = "my ssh host";
String sshuser = "my ssh user";
String dbuserName = "username db";
String dbpassword = "pass db";
String SshKeyFilepath = "/Users/mac/.ssh/id_rsa";
int localPort = 8740; // any free port can be used
String remoteHost = "ip db";
int remotePort = 3306;
String localSSHUrl = "localhost";
/***************/
String driverName = "com.mysql.jdbc.Driver";
try {
java.util.Properties config = new java.util.Properties();
JSch jsch = new JSch();
session = jsch.getSession(sshuser, sshHost, 22);
jsch.addIdentity(SshKeyFilepath);
config.put("StrictHostKeyChecking", "no");
config.put("ConnectionAttempts", "3");
session.setConfig(config);
session.connect();
System.out.println("SSH Connected");
Class.forName(driverName).newInstance();
int assinged_port = session.setPortForwardingL(localPort, remoteHost, remotePort);
System.out.println("localhost" + assinged_port + " -> " + remoteHost + ":" + remotePort);
System.out.println("Port Forwarded");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void connectToDataBase(String dataBaseName) throws SQLException {
String dbuserName = "username db";
String dbpassword = "pass db";
int localPort = 8740; // any free port can be used
String localSSHUrl = "ip db"; //since ssh connected i guess to put ip db
try {
//mysql database connectivity
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setServerName(localSSHUrl);
//dataSource.setPortNumber(localPort);
dataSource.setUser(dbuserName);
dataSource.setAllowMultiQueries(true);
dataSource.setPassword(dbpassword);
dataSource.setDatabaseName(dataBaseName);
connection = dataSource.getConnection();
System.out.print("Connection to server successful!:" + connection + "\n\n");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void closeConnections() {
CloseDataBaseConnection();
CloseSSHConnection();
}
public static void CloseDataBaseConnection() {
try {
if (connection != null && !connection.isClosed()) {
System.out.println("Closing Database Connection");
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void CloseSSHConnection() {
if (session != null && session.isConnected()) {
System.out.println("Closing SSH Connection");
session.disconnect();
}
}
// works ONLY FOR single query (one SELECT or one DELETE etc)
public static ResultSet executeMyQuery(String query, String dataBaseName) {
ResultSet resultSet = null;
try {
connectToServer(dataBaseName);
Statement stmt = (Statement) connection.createStatement();
resultSet = stmt.executeQuery(query);
System.out.println("Database connection success");
} catch (SQLException e) {
e.printStackTrace();
}
return resultSet;
}
public static void DeleteOrganisationReferencesFromDB(String organisationsLike) {
try {
connectToServer("ServerName");
Statement stmt = (Statement) connection.createStatement();
ResultSet resultSet = stmt.executeQuery("select * from DB1");
String organisationsToDelete = "";
List<String> organisationsIds = new ArrayList<String>();
// create string with id`s values to delete organisations references
while (resultSet.next()) {
String actualValue = resultSet.getString("id");
organisationsIds.add(actualValue);
}
for (int i = 0; i < organisationsIds.size(); i++) {
organisationsToDelete = " " + organisationsToDelete + organisationsIds.get(i);
if (i != organisationsIds.size() - 1) {
organisationsToDelete = organisationsToDelete + ", ";
}
}
stmt.executeUpdate(" DELETE FROM `DB1`.`table1` WHERE `DB1`.`table1`.`organisation_id` in ( " + organisationsToDelete + " );");
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeConnections();
}
}
public static List<String> getOrganisationsDBNamesBySubdomain(String organisationsLike) {
List<String> organisationDbNames = new ArrayList<String>();
ResultSet resultSet = executeMyQuery("select `DB`.organisation.dbname from `DB1`.organisation where subdomain like '" + organisationsLike + "%'", "DB1");
try {
while (resultSet.next()) {
String actualValue = resultSet.getString("dbname");
organisationDbNames.add(actualValue);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeConnections();
}
return organisationDbNames;
}
public static List<String> getAllDBNames() {
// get all live db names incentral DB
List<String> organisationDbNames = new ArrayList<String>();
ResultSet resultSet = executeMyQuery("show databases", "DB1");
try {
while (resultSet.next()) {
String actualValue = resultSet.getString("Database");
organisationDbNames.add(actualValue);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeConnections();
}
return organisationDbNames;
}
public static void deleteDataBasesByName(List<String> DataBasesNamesList) {
try {
connectSSH();
int dataBasesAmount = DataBasesNamesList.size();
for (int i = 0; i < dataBasesAmount; i++) {
connectToDataBase(DataBasesNamesList.get(i));
Statement stmt = (Statement) connection.createStatement();
stmt.executeUpdate("DROP database `" + DataBasesNamesList.get(i) + "`");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
CloseDataBaseConnection();
closeConnections();
}
}
but the result in console, no sign that query is executed
*the query is on another file
conn.connectSSH();
conn.executeMyQuery("select shade_item FROM nubr_product_shade WHERE shade_id=1", "database_name");
SSH Connected
localhost8740 -> 172.xx.x.xx:3306
Port Forwarded
Why you not do that with operating system utils ?
for example (MySQL Database) :
ssh -R 3306:127.0.0.1:3306 username#server.com -NnT
now jdbc connection to localhost with port 3306 .

ClassNotFoundException java

I have a doubt about Class Not Found Exception. I've added all the jars in my file but I cant seem to make it work. I've added the mysql-connector.jar in my project. DOes anyone know how to make it right?
try {
String driverName = "com.mysql.jdbc.Driver";
Class.forName(driverName);
String serverName = "localhost";
String mydatabase = "UFRJSocial";
String url = "jdbc:mysql://" + serverName + "/" + mydatabase;
String username = "root";
String password = "";
connection = DriverManager.getConnection(url, username, password);
if (connection != null) {
status = ("STATUS--->Connected!");
} else {
status = ("STATUS--->The connection failed");
}
return connection;
} catch (ClassNotFoundException e) {
System.out.println("The specified driver was nor found");
//THIS IS THE LINE THAT MY CONSOLE IS SHOWING
return null;
} catch (SQLException e) {
System.out.println("it was not possible to connect to the database.");
return null;
}
Take a look at this code please:
enter code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import app.dao.connector.DatabaseManager;
public class MySQLDatabaseManager implements DatabaseManager{
#Override
public Connection getConnection() {
final String USER_NAME ="root";
final String PASSWORD = "1234";
final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final String JDBC_URL = "jdbc:mysql://localhost:3306/inventory system";
Connection conn = null;
try{
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(JDBC_URL, USER_NAME, PASSWORD);
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}
return conn;
}
As You can see, I tried to declare all my variables outside the try and catch block. In declaring the JDBC_URL specify your database.
I've managed to make it work. It was missing the mysql.jar file in the Web-INF folder.

Connect to MySQL over SSH using Java

I want to connect to MySQL database on Amazon EC2 server using Java. I am able to create ssh tunnel using Jsch library and forward ports to that server, however connecting to DB always ends with exception
java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
I think i am stuck in the same situation as Hei (SSH tunneling to remote access MySQL database)
Here is my code:
public static void main(final String[] args) throws SQLException {
final int lport = 3306;
final String host = "xxx.xxx.xxx.xxx";
final String rhost = "xxx.xxx.xxx.xxx";
final int rport = 3306;
final String user = "user";
final String dbuserName = "user";
final String dbpassword = "password";
final String dburl = "jdbc:mysql://localhost:" + rport + "/information_schema?useUnicode=true&characterEncoding=UTF-8";
final String driverName = "com.mysql.jdbc.Driver";
Session session = null;
try {
//Set StrictHostKeyChecking property to no to avoid UnknownHostKey issue
final java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
final JSch jsch = new JSch();
session = jsch.getSession(user, host, 22);
jsch.addIdentity("path\\to\\pemfile.pem");
session.setConfig(config);
session.connect();
System.out.println("Connected");
final 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).newInstance();
dbConn = DriverManager.getConnection(dburl, dbuserName, dbpassword);
System.out.println("Database connection established");
System.out.println("DONE");
} catch (final Exception 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();
}
}
}
Can anyone help to solve this problem? Thanks
I've got exactly the same problem using AppFog (in front of AWS). The only way I could workaround this issue was dropping the following from my connection string:
"?useUnicode=true&characterEncoding=UTF-8"
Off course, you should be sure that this will not affect your application requirements.

Server thread hang

I use a thread to serve the client but when I remove the command handler.out.flush (on Server class), the thread hangs. I've tried searching on google but still not helping. I think the problem lies in the communications socket but I still have not got the right solution.
I want to make a simple login and registration functions so i used 2 class, Server and MysqlConn. The Server class receives incoming data (user profile - username, password, etc) from the client over the socket. After receiving, the data will be sent to MysqlConn class. The function of MysqlConn class is to check against the data and access my sql database to match them. If data and database match, then login process is succsses.
The format of data sent by the client is:
"login."+"name."+ "password." +"\n";
The following is the contents of Server class:
public class Server {
public static void main(String[] args)throws IOException, InstantiationException,
IllegalAccessException {
ServerSocket servsocket = null;
Socket sock = null;
try {
servsocket = new ServerSocket(28000);
while(true){
sock = servsocket.accept();
System.out.println(servsocket.isBound());
ChatThread thread = new ChatThread(sock);
String portnum = Integer.toString(sock.getPort());
thread.run(portnum);
}
} catch (IOException ioe) {
}
finally{
try {
servsocket.close();
} catch (IOException ioe) {
}
}
}
}
class ChatThread extends Thread{
static Vector<ChatThread> chatthread = new Vector<ChatThread>(10);
private BufferedReader in;
private PrintWriter out;
public ChatThread (Socket socket) throws IOException {
in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(
new OutputStreamWriter(socket.getOutputStream())); }
public void run(String portnum){
String line;
synchronized(chatthread) {
chatthread.addElement(this); }
try {
line = in.readLine()+portnum;
String[] teksmasuk = line.split("\\.");
for(int i = 0; i < chatthread.size(); i++) {
synchronized(chatthread) {
ChatThread handler =
(ChatThread)chatthread.elementAt(i);
handler.out.println(line + "\r");
handler.out.flush();
if
(teksmasuk[0].contentEquals("reg")||teksmasuk[0].contentEquals("login")
||teksmasuk[0].contentEquals("logout")) {
if(teksmasuk[0].contentEquals("reg")){
}
else
if(teksmasuk[0].contentEquals("login")){
}
MysqlConn sqlcon = new MysqlConn();
String hasil = sqlcon.register(line);
}
else{
}
}
}
} catch(IOException ioe) {
ioe.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
finally {
synchronized(chatthread) {
chatthread.removeElement(this);
}
}
}
}
MysqlConn class:
public class MysqlConn{
String dbn = "chat_db";
String URL = "jdbc:mysql://localhost/"+dbn ;
String usr = "root";
String pwd = "";
private String result;
boolean checkname = false;
boolean checkemail = false;
boolean checkpass = false;
private Connection con = null;
private String dbnama;
private String dbpass;
public String register(String line) throws InstantiationException,
IllegalAccessException, IOException, ClassNotFoundException{
String[] messagein =
line.split("\\.");
MysqlConn regs = new MysqlConn();
regs.login(messagein);
return result;
}
public void login (String[] messagein) throws InstantiationException,
IllegalAccessException{
if(messagein[0].contentEquals("login")) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(URL,usr,pwd);
Statement statement =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rslset = statement.executeQuery("select * from user");
int rs = statement.executeUpdate("update user set port="+
"'"+messagein[3] +"'" + "where nama = "
+ "'" + messagein[1] + "'" + "and password = " + "'"
+messagein[2] +"'" );
MysqlConn regs = new MysqlConn();
regs.check_status_login(messagein);
} catch (ClassNotFoundException e) {
System.out.println("Error #1:" + e.getMessage());
System.exit(0);
} catch(SQLException e){
System.out.println("Error #2:" + e.getMessage());
System.exit(0);
}
}
}
public void check_status_login (String[] messagein) throws InstantiationException,
IllegalAccessException, ClassNotFoundException{
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(URL,usr,pwd);
Statement statement =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rslset = statement.executeQuery("select * from user");
while(rslset.next()) {
String dbname = rslset.getString("nama");
String dbpass = rslset.getString("password");
if((messagein[1].contentEquals(dbnama))){
+ messagein[1]+ "\r" + "Password from database: "+dbpass + "\r" +
"Password from client: "+ messagein[2]+ "\n");
checknama = true;
}
else if (messagein[2].contentEquals(dbpass)){
checkpass = true;
}
}
} catch (SQLException e1) {
+ e1);
}
if (!checknama){
hasil = "gagal";
}
else if (!checkpass)
{
hasil = "gagal";
}
else {
hasil = "login sukses";}
}
}
The java docs clearly say that the constructor you are using for PrintWriter will not cause automatic flushing. This means that you nead to call flush to send data out of the printwriter manually. Alternatively you can do
out = new PrintWriter( new OutputStreamWriter(socket.getOutputStream()) , true );
to enable automatic flushing. I generally prefer to do flush streams manually anyways.
As far as your question regarding your "application gets stuck" , you will need to provide more information such as how many clients connected and what exactly happens before the system hangs

Categories