JDBC,JDBC连接池和JNDI
2009-02-14 09:48
393 查看
最初级的用法,也可以说是菜鸟 显式地把 JDBC 驱动程序、数据库 URL 以及用户名和口令编码到程序中
记得我服务过的第一家公司把 jdbc:mysql://localhost?user=root&password=12345 定义为一个类里的全局性静态变量,从而如果要修改只修改这个变量就可以,而无需找遍每个数据库连接。从某种意义上讲,这也是一种比较优雅的做法其实这种方法跟读.properties配置文件有异曲同工之妙,只是后者可能更优雅一些而已。对数据库而言,没有性能方面的提升。
更高级一点的使用jdbc连接池(我自己做的小项目都是这种模式的)
再来看看怎么使用 JNDI 得到数据源
当然喽,使用JNDI还要配置一下web.xml,<resource-ref> 标签的意思就是“这个组件依赖于外部资源”
Connection conn=null; String url = "jdbc:mysql://localhost?user=root&password=12345"; try { Class.forName("com.mysql.jdbc.Driver", true, Thread.currentThread().getContextClassLoader(url)); conn=DriverManager.getConnection(); /* use the connection here */ c.close(); }catch(Exception e) { e.printStackTrace(); }finally { if(conn!=null) { try { conn.close(); } catch(SQLException e) {} } }
记得我服务过的第一家公司把 jdbc:mysql://localhost?user=root&password=12345 定义为一个类里的全局性静态变量,从而如果要修改只修改这个变量就可以,而无需找遍每个数据库连接。从某种意义上讲,这也是一种比较优雅的做法其实这种方法跟读.properties配置文件有异曲同工之妙,只是后者可能更优雅一些而已。对数据库而言,没有性能方面的提升。
更高级一点的使用jdbc连接池(我自己做的小项目都是这种模式的)
//下面的getConnection()方法和freeConnection() //就是连接池实现的方法 Connection con = null; PreparedStatement pstm = null; ResultSet rs = null; try{ conn = getConnection(); String querySQL = "select * from user"; pstm = conn.prepareStatement(querySQL); rs = pstm.executeQuery(); while(rs.next()){ System.out.println("user name is " + rs.getSTring(1)); } }catch(SQLException ex){ ....... }finally{ freeConnection(); }
再来看看怎么使用 JNDI 得到数据源
Connection conn=null; try { Context ctx=new InitialContext(); Object datasourceRef=ctx.lookup("java:comp/env/jdbc/mydatasource"); DataSource ds=(Datasource)datasourceRef; Connection c=ds.getConnection(); /* use the connection */ c.close(); } catch(Exception e) { e.printStackTrace(); } finally { if(conn!=null) { try { conn.close(); } catch(SQLException e) { ... } } }
当然喽,使用JNDI还要配置一下web.xml,<resource-ref> 标签的意思就是“这个组件依赖于外部资源”
<resource-ref> <description>Dollys DataSource</description> <res-ref-name>jdbc/mydatasource</res-ref-name> <res-ref-type>javax.sql.DataSource</res-ref-type> <res-auth>Container</res-auth> </resource-ref>
相关文章推荐
- JDBC工作流程、JNDI连接池
- 汇总 Hibernate 与 jdbc,jndi+dbcp, proxool ,c3p0 连接池的配置
- Tomcat 7 新的连接池 —— Tomcat jdbc pool + JNDI
- 方立勋_30天掌握JavaWeb_JDBC、连接池、JNDI(三)
- JDBC第五章知识点总结——JDBC高级特性3--JNDI,连接池,分布式事务
- JNDI与JDBC比较以及连接池的技术
- JNDI与JDBC比较以及连接池的技术
- JDBC高级特性3--JNDI,连接池,分布式事务
- JNDI与JDBC比较以及连接池的技术
- JNDI与JDBC比较以及连接池的技术 .
- JDBC (c3p0、dbcp、jndi及不使用连接池)
- JNDI与JDBC比较以及连接池的技术
- JNDI与JDBC比较以及连接池的技术
- JDBC第五章知识点总结——JDBC高级特性3--JNDI,连接池,分布式事务
- JNDI(Java 命名和目录接口)(二)--JDBC2.0扩展API
- 什么是DataSource?入手tomcat-jdbc连接池
- JDBC之连接池
- 数据库_jdbc_连接池+框架_改造分页案例
- [转]JDBC与连接池
- JDBC连接池之C3P0