Java switch connection when connection error occured (Failover connection) - java

Is it possible switch to second connection source with JAVA when sql connection error occured ?
protected Connection dbConnect(String jdbcProvider) throws
MbException,SQLException{
return getJDBCType4Connection(jdbcProvider,JDBC_TransactionType.MB_TRANSACTION_AUTO);
}
protected Connection dbStandByConnect(String jdbcProvider,String jdbcProvider2) throws MbException{
Connection con=null;
try {
con= dbConnect(jdbcProvider);
} catch (SQLException e) {
try {
con= dbConnect(jdbcProvider2);
} catch (SQLException sqlEx) {
throw new RuntimeException(sqlEx);
}
}
return con;
}
I have no idea if it is right way or not ? Do you have any suggestions as to how I can make this work?
Thanks in advance.

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

Connect with DB2 from Java

I try to connect to db2 from java, here is my code:
public class Db2Connection {
public static void main(String[] args) {
String jdbcClassName="com.ibm.db2.jcc.DB2Driver";
String url="jdbc:db2://localhost:50001/TEST";
String user="user1";
String password="pass";
System.out.println("before try-catch");
Connection connection = null;
try {
System.out.println("try");
//Load class into memory
Class.forName(jdbcClassName);
//Establish connection
System.out.println("before conn");
connection = DriverManager.getConnection(url, user, password);
System.out.println("after conn");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(connection!=null){
System.out.println("Connected successfully.");
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
To be clear, I add db2jcc.jar to my project and run code with valid url. Program cannot jump over line:
connection = DriverManager.getConnection(url, user, password);
I receive no errors or exception, application just not execute. I have no idea how deal with it, can anyone help me?
Try, after removing colon like :
String url="jdbc:db2//localhost:50001/TEST";

How to create a connection to the 2 Mysql servers?

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;
}

Try with resources Statement for JDBC in java

Useful piece of code for Hive JDBC:
Connection con = null;
Statement stmt = null
try {
Class.forName("org.apache.hive.jdbc.HiveDriver");
con = DriverManager.getConnection(connectionUri, userName, password);
stmt = con.createStatement();
stmt.executeUpdate(query);
} catch (ClassNotFoundException cex) {
cex.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
I want to remove try - catch in finally block.
So I tried The try-with-resources Statement.
try (Class.forName("org.apache.hive.jdbc.HiveDriver");
Connection con = DriverManager.getConnection(connectionUri, userName, password);
Statement stmt = con.createStatement();){
stmt.executeUpdate(query);
} catch (ClassNotFoundException cex) {
cex.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
I think this is not the right way.
Class.forName("org.apache.hive.jdbc.HiveDriver") should not be in try. Should I make a separate try-catch for this?
try {
Class.forName("org.apache.hive.jdbc.HiveDriver");
} catch (ClassNotFoundException cex) {
cex.printStackTrace();
}
try (Connection con = DriverManager.getConnection(connectionUri, userName, password);
Statement stmt = con.createStatement();){
stmt.executeUpdate(query);
} catch (SQLException e) {
e.printStackTrace();
}
Is this right way or am I missing any thing?
The idea behind try-with-ressource is to close an AutoCloseable class.
So every usage of a class which should be closed after using it (a Ressource) can be used with try-with-ressource (like Connection for example). You don't have to take care of closing it manually (in an finally block for example).
So yes, your idea is right:
try/catch for Class.forName("org.apache.hive.jdbc.HiveDriver"); - because this is not AutoCloseable
try-with-ressource for Connection con = DriverManager.getConnection(connectionUri, userName, password);
Statement stmt = con.createStatement();- because Connection and Statement implement AutoCloseable
Reference:
https://docs.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html
When you're using Java 6 or better and the Apache Hive JDBC driver is JDBC 4 compliant or better* then you do not need the Class.forName("org.apache.hive.jdbc.HiveDriver") stuff at all.
Therefore you can just remove the entire try/catch block from your second solution and you're good to go with just:
try (Connection con = DriverManager.getConnection(connectionUri, userName, password);
Statement stmt = con.createStatement()) {
stmt.executeUpdate(query);
} catch (SQLException e) {
e.printStackTrace();
}
* Which is the case for version 1.2.0 or newer of the Hive JDBC driver

Connection Java to sqlite (Netbeans)

I'm having a problem, not sure how to fix:
connection code:
public class sqliteConnection {
Connection conn = null;
public static Connection dbConnector() {
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:V:\\Database\\table.sqlite");
JOptionPane.showMessageDialog(null, "Conected to Database");
return conn;
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
and where I'm using this connection:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
String sql="insert into test (test) value (?)";
PreparedStatement pst=conn.prepareStatement(sql);
pst.setString(1, Test.getText());
}catch (Exception e){
e.printStackTrace();
}
}
I'm getting a SQLITE_ERROR SQL error or missing database (near "value": syntax error) error, and I cant tell where the error could come from. I just created a test table in sqlite to test the connection, with one column which is a 'TEXT' named test. any help?

Categories