用jndi做数据库链接
package com.newer.lee.ajax.dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class DBUtil {
private static DataSource ds = null;
//从jndi中查找数据源,只做一次
static {
try {
Context ctx = new InitialContext();
ds = (DataSource)ctx.lookup("java:comp/env/jdbc/myDS");
}
catch (NamingException e) {
e.printStackTrace();
}
}
//得到数据库的连接
public static Connection getCon() throws SQLException {
return ds.getConnection();
}
//释放资源
public static void release(ResultSet rs, Statement st, Connection con) {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
context.xml配置如下
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/myDS" auth="Container"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@127.0.0.1:1521:ADMIN" username="system"
password="system" maxActive="20" maxIdle="10" maxWait="-1" />
</Context>
web.xml配置如下
<resource-ref>
<res-ref-name>jdbc/myDS</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
这样就可以实现数据库连接操作了呵呵