日期:2014-05-16 浏览次数:20468 次
package DAO; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.sql.SQLException; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; public class DAOConnection { private static DataSource ds = null; public static DataSource getDataSource() throws Exception{ long start = System.currentTimeMillis(); if (ds == null) { Context initContext = new InitialContext(); //初始化 if (initContext == null) throw new Exception("No Context"); Context envContext = (Context) initContext.lookup("java:/comp/env"); ds = (DataSource) envContext.lookup("jdbc/BookDb"); //需要与context里的 目录一致 long end = System.currentTimeMillis(); System.out.println(end-start); //测试连接数据库时间 } return ds;[/i] } public static Connection getConnection() { try { Connection conn = getDataSource().getConnection(); if (conn != null) return conn; } catch (Exception e){ e.printStackTrace(); } return null; } public static void close(Connection conn, Statement st ,ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException ex) {} } if (st != null) { try { st.close(); } catch (SQLException ex) {} } if (conn != null) { try { conn.close(); } catch (Exception ex) {} } } }