繁体   English   中英

数据源与简单连接数据库

[英]datasource vs simple connection database

最好的方法是什么?我需要连接许多远程数据库来解决来自Restful Web服务的许多请求。 我在想两种解决方案:

  1. 每个远程数据库一个数据源,与每个数据源的连接就像单例模式。

  2. 每个远程数据库一个简单的连接,与每个数据库建立连接的单例模式。

第一种方法的一个示例是这样的(víamsdn):

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

这取决于您的数据库和查询之间的关系。 如果对单个数据库(例如用户数据库)有很多查询,那么您将需要多个连接,否则最终将导致线程阻塞该资源。

最灵活的方法是为每个远程数据库都有一个连接池,并对其进行配置,以使它们具有适当数量的可用连接,这要考虑到在任何一次REST事务中可能被查询。

一个好的开始可能是查看Tomcat数据源池。 请注意,无论是否将Tomcat用作Web服务器,都可以使用它。

一个Connection不能被多个线程同时使用,而一个DataSource可以。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM