您的位置:首页 > 其它

JDBC,JDBC连接池和JNDI

2009-02-14 09:48 393 查看
最初级的用法,也可以说是菜鸟 显式地把 JDBC 驱动程序、数据库 URL 以及用户名和口令编码到程序中

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