首先可选择将其配置到tomcat的安装目录下的context.xml中,也可以将其安装到eclipseEE生成的Servers中的tomcat的context.xml中,全凭喜欢吧。
在<Context></Context>中直接创建配置
<Resource auth="Container" driverClassName="com.mysql.jdbc.Driver" maxIdle="30" maxTotal="10" maxWaitMillis="10000" name="jdbc/MySQL" password="root" type="javax.sql.DataSource" url="jdbc:mysql://localhost:3305/secondaryMarket" username="root"/>
之后可编写方法,
public Connection getConnection() {
// TODO Auto-generated method stub
Connection conn = null;
try {
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:/comp/env/jdbc/MySQL");
conn = ds.getConnection();
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
每次通过这里获取数据库的连接,即可实现连接池的作用!