简介
前段时间用jdbc连接池,在这里记录下
1、利用jdni配置数据源
在Web项目的META-INF文件夹中新建context.xml文件,内容为:
<?xml version="1.0" encoding="UTF-8"?> <Context> <Resource name="jdbc/myDataSource" auth="Container" type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/testDB" username="jacky" password="admin" maxActive="20" maxIdle="10" maxWait="10000"/> </Context
这种方式就不会依赖于tomcat,此外还可以在tomcat的conf目录下context.xml配置数据源
2、在web项目的web.xml添加如下配置
<resource-ref> <description>JNDI DataSource</description> <res-ref-name>jdbc/myDataSource</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth>
</resource-ref>
3、测试
package org.gsfan.db; import java.sql.Connection; import java.sql.SQLException; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; public class DBConnect { private Connection connection = null; public DBConnect() { } public Connection getConnection() { try { connection = getConnectionUseJNDI(); } catch (NamingException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return connection; } public Connection getConnectionUseJNDI() throws NamingException, SQLException{ Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/myDataSource"); Connection conn = ds.getConnection(); return conn; } }
}
}