最好的方法是什么?,我需要连接许多远程数据库来解决来自 Restful Web 服务的许多请求。我在想两个解决方案:
每个远程数据库一个数据源,与每个数据源的连接将类似于单例模式。
每个远程数据库一个简单的连接,只是一个连接每个数据库的单例模式。
第一种方法的一个例子是这样的(通过 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;
}