您的位置:首页 > 其它

使用DataSource小结

2017-07-28 09:49 274 查看
DataSource接口(javax.sql.DataSource)替代DriverManager获取Connection的方法,有以下好处:
可以在部署时灵活更换Connection实现;
可以更好的屏蔽数据库的相关性。

以下以Oracle为例说明。

 

使用厂商DataSource

数据库厂商在提高JDBC2.0和以上版本的JDBC驱动中应该包含厂商的DataSource实现。

OracleDataSource ods = new OracleDataSource();

ods.setUser(“my_user”);

ods.setPassword(“my_password”);

ods.setURL(“jdbc:oracle:thin:@<database>”);

Connection conn = ods.getConnection();

第三方DataSource

第三方厂商也可提供DataSource实现,比如免费开源的有DBCP,C3P0和proxool等,中间件厂商比如ibm的websphere,bea的weblogic等也都有实现。

以下是DBCP的示例:

BasicDataSource basicDataSource = new BasicDataSource(); basicDataSource.setDriverClassName(“oracle.jdbc.OracleDriver”); basicDataSource.setUrl(“jdbc:oracle:thin:@<database>”); basicDataSource.setUsername(“user”);basicDataSource.setPassword(“password”); Connection
connection=basicDataSource.getConnection();

结合JNDI的DataSource

以tomcat为例,将数据库驱动库复制到{tomcat}/commmon/lib目录下。

配置{tomcat}/conf/context.xml文件,加入:

<Resource name=”jdbc/demo” auth=”Container” type=”javax.sql.DataSource”

        driverClassName=”org.apache.derby.jdbc.ClientDriver”

        url=”jdbc:derby://localhost:1527/demo”

        username=”test”

        password=”test”

        maxActive=”2″

        maxIdle=”1″

        removeAbandoned=”true”

        maxWait=”300″ />

在程序中访问DataSource:

Context initContext = new InitialContext();

// 注意: 以下写法只适用于tomcat(Java:/comp/env).

Context envContext = (Context) initContext.lookup(“java:/comp/env”);

dataSource = (DataSource) envContext.lookup(“jdbc/demo”);

 

配置内容也可以加到webapp/META-INF/context.xml文件中,这样更便于打包部署。

 

 

<%@page import="java.sql.*, javax.sql.*, javax.naming.*"%>

<html>

<head>

<title>Using a DataSource</title>

</head>

<body>

<h1>Using a DataSource</h1>

<%
    DataSource ds = null;
    Connection conn = null;
    ResultSet result = null;
    Statement stmt = null;
    ResultSetMetaData rsmd = null;
    try{
      Context context = new InitialContext();
      Context envCtx = (Context) context.lookup("java:comp/env");
      ds =  (DataSource)envCtx.lookup("jdbc/address");
      if (ds != null) {
        conn = ds.getConnection();
        stmt = conn.createStatement();
        result = stmt.executeQuery("SELECT * FROM AddressList");
       }
     }
     catch (SQLException e) {
        System.out.println("Error occurred " + e);
      }
      int columns=0;
      try {
        rsmd = result.getMetaData();
        columns = rsmd.getColumnCount();
      }
      catch (SQLException e) {
         System.out.println("Error occurred " + e);
      }
 %>
 <table width="90%" border="1">
   <tr>
   <% // write out the header cells containing the column labels
      try {
         for (int i=1; i<=columns; i++) {
              out.write("<th>" + rsmd.getColumnLabel(i) + "</th>");
         }
   %>
   </tr>
   <% // now write out one row for each entry in the database table
         while (result.next()) {
            out.write("<tr>");
            for (int i=1; i<=columns; i++) {
              out.write("<td>" + result.getString(i) + "</td>");
            }
            out.write("</tr>");
         }
 
         // close the connection, resultset, and the statement
         result.close();
         stmt.close();
         conn.close();
      } // end of the try block
      catch (SQLException e) {
         System.out.println("Error " + e);
      }
      // ensure everything is closed
    finally {
     try {
       if (stmt != null)
        stmt.close();
       }  catch (SQLException e) {}
       try {
        if (conn != null)
         conn.close();
        } catch (SQLException e) {}
    }
 
    %>

</table>

</body>

</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: