How to create a connection to the 2 Mysql servers? - java

I'm totally noob! I have automative test framework previously written for single Mysql server with 2 database on it. And DB connection was looked like
public static Connection getConnection() {
if (conn == null) {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://"
+ PropertyHandler.getInstance().getValue(PropertyKeys.dbHost)
+ ":"
+ PropertyHandler.getInstance().getValue(PropertyKeys.dbPort),
PropertyHandler.getInstance().getValue(PropertyKeys.dbUser),
PropertyHandler.getInstance().getValue(PropertyKeys.dbPass));
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
return conn;
}
public static void closeConnection() {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
But now they are on different IPs . Please provide simple example how to fix it. Thanks.

Java DB connection is just a Object. you can create 2 connection Objects for 2 Mysql Servers.
you have getConnection() method created. so you just need to change the method to accept connection parameters.
for example:
Connection db1 = getConnection(server_ip, db, username, password);
Connection db2 = getConnection(server_ip2, db, username2, password2);
public static Connection getConnection(String ip, String db, String user, String pass) {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://"+ip+"/"+db+"?" +
"user="+user+"&password="+pass);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
return conn;
}

Related

HSQLDB never closes DB connection

I'm playing with this kind of database, and I've tried to close the HSQLDB connection after I used it, but it's still opened at the end.
Code:
//----This methods are in a specific connection class file
public static Connection conn = null;
public static Connection getConnection(){
try {
input = new FileInputStream("PathToMyPropertiesFile");
prop.load(input);
//The properties constants are correctly checked
Class.forName(prop.getProperty("DRIVER_HSQLDB"));
conn = DriverManager.getConnection(prop.getProperty("CONN_HSQLDB"));
}
catch(ClassNotFoundException | SQLException e) {
LOG.log(null,"Error: "+e);
}
catch (IOException ex) {
LOG.log(null,"FILE ERROR: "+ex);
}
finally {
if (input != null) {
try {
input.close();
} catch (Exception e) {
LOG.log(null,"CLOSE ERROR: "+e);
}
}
}
return conn;
}
public static boolean stopConn() {
try {
if(conn != null) {
conn.close();
System.err.println("\nCLOSE CONN\n"+conn);
return true;
}
}
catch (SQLException e) {
e.printStackTrace();
return false;
}
return false;
}
//========= the other class file with the methods to use the conneciton
public static boolean insertUser(String uName, String uEmail){
Connection con;
con = ConnectionDB.getConnection();
PreparedStatement ps = null;
try {
String consulta = "insert into USERS (\"NICK\",\"EMAIL\") VALUES(?,?);";
ps = con.prepareStatement(consulta);
System.err.println(ps);
ps.setString(1,uName);
ps.setString(2,uEmail);
System.err.println("\nASSIGNATION\n"+ps);
if(ps.executeUpdate() == 1) {
System.err.println("\nTRUE\n");
return true;
}
}
catch(SQLException e) {
e.printStackTrace();
}
finally {
try {
System.err.println("\nFINALLY\n"+ps);
if(ps != null) {
ps.close();
System.err.println("\nCLOSE PS\n"+ps);
}
if(con != null) {
con.close();
System.err.println("\nCLOSE CON\n"+con);
if(ConnectionDB.stopConn()) {
System.err.println("\nALL IS OK\n"+ConnectionDB.conn);
}
else {
System.err.println("\nMEEEEKKKK!!!\n"+ConnectionDB.conn);
}
}
}
}
return false;
}
The console give me this results, and I don't know why never the connection is closed because I tried to close it twice. If someone has an idea please tell me.
org.hsqldb.jdbc.JDBCPreparedStatement#4501280b[sql=[insert into USERS ("NICK","EMAIL") VALUES(?,?);], parameters=[[null], [null]]]
ASSIGNATION
org.hsqThis is my cldb.jdbc.JDBCPreparedStatement#4501280b[sql=[insert into USERS ("NICK","EMAIL") VALUES(?,?);], parameters=[[extra], [extra#mail.com]]]
TRUE
FINALLY
org.hsqldb.jdbc.JDBCPreparedStatement#4501280b[sql=[insert into USERS ("NICK","EMAIL") VALUES(?,?);], parameters=[[extra], [extra#mail.com]]]
CLOSE PS
org.hsqldb.jdbc.JDBCPreparedStatement#4501280b[closed]
CLOSE CON
org.hsqldb.jdbc.JDBCConnection#3e5b87f5
CLOSE CONN
org.hsqldb.jdbc.JDBCConnection#3e5b87f5
ALL IS OK
org.hsqldb.jdbc.JDBCConnection#3e5b87f5
Closing a JDBC connections does not close an in-process database. This allows you to open and close different connections during the runtime of your application.
You need to execute a JDBC Statement to shutdown the database. The SQL statement to execute is "SHUTDOWN".
It is possible to add a connection property "shutdown=true" to the JDBC connection URL to force a quick shutdown when the last connection to the in-process database is closed. But this is mainly useful for readonly or test databases. A full SHUTDOWN allows the database to open quickly the next time a connection is made.
See the Guide http://hsqldb.org/doc/2.0/guide/running-chapt.html#rgc_inprocess

JDBC connection in Java with Eclipse ( when a method calling a method)

I'm trying to connect to my DB using JDBC. I wanted to make a method for connection and another method for selecting data. I am getting a red line in Eclipse on the 'Connection con = connectDB();' part. ( See also attached) Cany anyone give me advice?
public class DBJdbc {
//Statement stmt = null;
// connecting to DB
public void connectDB() {
//Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://****/SAC?useSSL=false&serverTimezone=UTC", "***", "***");
}
catch(SQLException e) {
e.printStackTrace();
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}
}
// a method for selecting DB
public static void select() {
//connectDB();
String sql = "SELECT * from SAC_SUR";
try(Connection con = connectDB(); // I'm getting a red line here)
PreparedStatement pstmt = con.prepareStatement(sql)){
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
int id = rs.getInt(1);
String name = rs.getString(2);
System.out.println("Id = " + id + "name = " + name);
} //while
} catch(SQLException e) {
System.out.println(e.getMessage());
}
}
red line here!!!
connectDB() method is of void type and not returning anything but when you are calling the method, you are assigning it to variable con. So you need to change the return type of connectDb to the Connection type.
public Connection connectDB() {
Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://****/SAC?useSSL=false&serverTimezone=UTC", "***", "***");
}
catch(SQLException e) {
e.printStackTrace();
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}
return con;
}
You are trying to call non-static method into the static area, which is not allowed in Java. So I made this method static and returning the database connection.
Please update the below method into your code. It will resolve your problem.
public static Connection connectDB() {
Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://****/SAC?useSSL=false&serverTimezone=UTC", "", "");
} catch(SQLException e) {
e.printStackTrace();
} catch(ClassNotFoundException e) {
e.printStackTrace();
}
return con;
}

SQLite Java JDBC Insert

Following is my Java code. In linux, it is working fine but in Windows I'm unable to insert data into the database on local disk. In NetBeans get it all right but .jar file not. JDBC driver see be good.
Connecting to database:
public static Connection connectToDb() {
try {
Connection connection = null;
DriverManager.registerDriver(new org.sqlite.JDBC());
//LINUX PATH
if (OSDetector.isLinux()) {
connection = DriverManager.getConnection("jdbc:sqlite:/home/" + userNameLinux + "/PDFMalwareDataAnalyser/DatabaseSQLite/database.db", NAME, PASSWORD);
//WINDOWS PATH
} else {
connection = DriverManager.getConnection("jdbc:sqlite:C:\\PDFMalwareDataAnalyser\\DatabaseSQLite\\database.db", NAME, PASSWORD);
}
connection.setAutoCommit(true);
if (connection != null) {
System.out.println("Otvorená.");
}
return connection;
} catch (SQLException e) {
System.err.println(e.getClass().getName() + e.getMessage());
// System.exit(0);
}
return null;
}
Insertion:
public void insertDataToDatabase(int idReport) throws SQLException {
connection = new SQLiteJDBC().connectToDb();
PreparedStatement insertCommunication = connection.prepareStatement("insert into table_communication values(?,?);");
insertCommunication.setString(2, communicationsFinal.toString());
try {
insertCommunication.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
insertCommunication.close();
connection.close();
System.out.println("1. --- Insert do tabuľky TABLE_COMMUNICATION OK ---");
}
Try this:
connection = DriverManager.getConnection("jdbc:sqlite:C:/PDFMalwareDataAnalyser/DatabaseSQLite/database.db")

cannot exexute SQL query wirh OJDBC and Oracle DB (but full working with posgtres JDBC and Postgres DB)

I wrote a java program which retrieve data from a PG gb, process them, and write them in an Oracle DB.
While the PG part is fully working, the Oracle one has issues.
I can connect to the DB, but every query ends with a rollback (ResultSet with Oracle is always null)
Of course i have both PG and Oracle JDBC driver.
Here are my DBs object and testing queries
private final static PostgresDB postgres = new PostgresDB("jdbc:postgresql://192.168.2.23:5432/T18CLEAN", "myPGUser", "myPGPasswd", true);
private final static OracleDB oracle = new OracleDB("jdbc:oracle:thin:#192.168.2.20:1521/EFFEVI.T18FV.IT", "myOracleUser", "myOraclePasswd");
private final static String testPostgres = "SELECT product_pricelist_item.x_product_name FROM public.product_pricelist_item;";
private final static String testOracle = "SELECT EFFEVI.PRESA_ORDINI.PO_CLIENTE FROM EFFEVI.PRESA_ORDINI;";
Then I setup the 2 connections:
PG:
public Connection getConnect() throws ClassNotFoundException {
System.out.println("-------- Posgres JDBC Connection Testing ------");
String url = c_url;
Connection conn = null;
Properties props = new Properties();
props.setProperty("user", user);
props.setProperty("password", passwd);
props.setProperty("ssl", boolToString(sslEnabled));
try{
Class.forName("org.postgresql.Driver");
System.out.println("Postgres JDBC Driver Registered!");
} catch(ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return null;
}
try {
conn = DriverManager.getConnection(url, props);
System.out.println("You made it, take control your Postgres database now!");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Failed to make connection to Postgres DB!");
}
return conn;
}
Oracle:
public Connection getConnect(){
Connection connection = null;
System.out.println("-------- Oracle JDBC Connection Testing ------");
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return connection;
}
System.out.println("Oracle JDBC Driver Registered!");
try {
connection = DriverManager.getConnection(c_url, user, passwd);
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return connection;
}
if (connection != null) {
System.out.println("You made it, take control your Oracle database now!");
return connection;
} else {
System.out.println("Failed to make connection to Oracle DB!");
}
return connection;
}
After all these pass i perform queries
public ResultSet executeCommand(Connection c, String command) {
Statement st = null;
ResultSet rs = null;
try {
st = c.createStatement();
rs = st.executeQuery(command);
} catch (SQLException e) {
}
if(rs==null){
System.out.println("Failed to Execute command " + command);
} else {
System.out.println("Command Executed: " + command);
}
return rs;
}
Assuming that there are no parameters error... What could it be? Any help?
Thank you very much
Remove a semicolon at the end of the query.
Use this:
private final static String testOracle =
"SELECT EFFEVI.PRESA_ORDINI.PO_CLIENTE FROM EFFEVI.PRESA_ORDINI";
instead of this one:
private final static String testOracle =
"SELECT EFFEVI.PRESA_ORDINI.PO_CLIENTE FROM EFFEVI.PRESA_ORDINI;";
Also don't silently "swallow" an exception in your code:
} catch (SQLException e) {
}
Rethrow the exception, or at least print the error to the log:
} catch (SQLException e) {
log.error("Error while executing query " + command, e);
throw new RuntimeException("Error while executing query " + command, e);
}

Returning the Connection from JDBC into a main method of Java?

Is it possible to return the type Connection?
And use it as a method passed by reference through out the program?
I find it makes the database interaction a lot easier if it is passed as a method.
public static Connection database(String database, String username, String password) {
String url = "jdbc:postgresql:" + database;
//LOAD DRIVER
try {
Class.forName("org.postgresql.Driver");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
//CONNECT TO DATABASE
try {
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
db = database("java_jdbc", "admin", "fake_password_1234");
}
You can do that.
Just remember to invoke close() on the connection to release its resources when done.
package mySystem;
import java.sql.*;
import javax.swing.*;
public class MySqlConnector {
Connection conn = null;
public static Connection ConnectDB() {
try {
Class.forName("com.mysql.jdbc.Driver"); //register jdbc driver
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/inventory_db", "root", "");
// JOptionPane.showMessageDialog(null, "Connected to db");
return conn;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}

Categories