分享

DB连接池管理编程举例

 最强火枪手 2009-02-20
DB连接池管理编程举例 import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.ConnectionPoolDataSource; import javax.sql.PooledConnection; public class MainClass { public static void main(String[] args) { Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { connection = getConnection(); // 操作连接 statement = connection.createStatement(); String selectEmployeesSQL = "SELECT * FROM employees"; resultSet = statement.executeQuery(selectEmployeesSQL); while (resultSet.next()) { printEmployee(resultSet); } } catch (Exception e) { e.printStackTrace(); } finally { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { } // nothing we can do } if (statement != null) { try { statement.close(); } catch (SQLException e) { } // nothing we can do } if (connection != null) { try { connection.close(); } catch (SQLException e) { } // nothing we can do } } } private static Connection getConnection() throws NamingException, SQLException { InitialContext initCtx = createContext(); String jndiName = "HrDS"; ConnectionPoolDataSource dataSource = (ConnectionPoolDataSource) initCtx.lookup(jndiName); PooledConnection pooledConnection = dataSource.getPooledConnection(); return pooledConnection.getConnection(); // 从池中得到连接 } private static InitialContext createContext() throws NamingException { Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory"); env.put(Context.PROVIDER_URL, "rmi://localhost:1099"); InitialContext context = new InitialContext(env); return context; } private static void printEmployee(ResultSet resultSet) throws SQLException { System.out.print(resultSet.getInt("employee_id")+", "); System.out.print(resultSet.getString("last_name")+", "); System.out.print(resultSet.getString("first_name")+", "); System.out.println(resultSet.getString("email")); } } 凡是有该标志的文章,都是该blog博主Caoer(草儿)原创,凡是索引、收藏 、转载请注明来处和原文作者。非常感谢。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多