What would be the best approach?, I need to connect many remote databases to resolve many requests from a Restful web service. I was thinking two solutions:
One datasource per remote database, and the connection to each datasource will be like a singleton pattern.
One simple connection per remote database, well just a singleton pattern to connect with each database.
One example of the first approach is like this (vía msdn):
import java.sql.*;
import com.microsoft.sqlserver.jdbc.*;
public class connectDS {
public static void main(String[] args) {
// Declare the JDBC objects.
Connection con = null;
CallableStatement cstmt = null;
ResultSet rs = null;
try {
// Establish the connection.
SQLServerDataSource ds = new SQLServerDataSource();
ds.setUser("UserName");
ds.setPassword("*****");
ds.setServerName("localhost");
ds.setPortNumber(1433);
ds.setDatabaseName("AdventureWorks");
con = ds.getConnection();
// Execute a stored procedure that returns some data.
cstmt = con.prepareCall("{call dbo.uspGetEmployeeManagers(?)}");
cstmt.setInt(1, 50);
rs = cstmt.executeQuery();
// Iterate through the data in the result set and display it.
while (rs.next()) {
System.out.println("EMPLOYEE: " + rs.getString("LastName") +
", " + rs.getString("FirstName"));
System.out.println("MANAGER: " + rs.getString("ManagerLastName") +
", " + rs.getString("ManagerFirstName"));
System.out.println();
}
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (cstmt != null) try { cstmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
System.exit(1);
}
}
}
For the second approach the singleton example could be:
public java.sql.Connection conn;
private static Statement statement;
public static MysqlConnect db;
private MysqlConnect() {
String url= "jdbc:mysql://localhost:3306/";
String dbName = "Banco";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "123456";
try {
Class.forName(driver).newInstance();
this.conn = (java.sql.Connection)DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to DataBase: " + dbName);
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException sqle) {
System.out.println("Error Inesperado en MysqlConnect" + sqle.toString());
}
}
/**
*Method for connect to a database
* @return MysqlConnect Database connection object
*/
public static synchronized MysqlConnect getDbCon() {
if ( db == null ) {
try {
db = new MysqlConnect();
statement = db.conn.createStatement();
} catch (SQLException ex) {
Logger.getLogger(MysqlConnect.class.getName()).log(Level.SEVERE, null, ex);
}
}
System.out.println("Connection to DB: OK");
return db;
}