會是什麼,最好的辦法?我需要連接多個遠程數據庫,以解決從RESTful Web服務的許多要求。我正在考慮兩種解決方案:數據源VS簡單的連接數據庫
每個遠程數據庫的一個數據源以及到每個數據源的連接將像單例模式一樣。每個遠程數據庫
一個簡單的連接,也只是一個單模式與每個數據庫連接。第一種方法的
一個實例是這樣的(通過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);
}
}
}
對於第二種方法的單身例子可以是:
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;
}