由于Tomcat中自带DBCP数据库连接池,所以在使用DBCP数据库连接池时,可以不用额外添加jar包(不过当然需要连接数据库的驱动包),只需要配置一下,就可以直接使用DBCP数据库连接池。
具体使用方法是在Web工程WebRoot–>META-INF目录下新建一个context.xml文件,配置文件内容如下:
<Context>
<Resource name="jdbc/mysql"
auth="Container"
type="javax.sql.DataSource"
maxActive="50"
maxWait="10000"
logAbandoned="true"
username="root"
password="root"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8"
/>
</Context>
现在就可以使用数据库连接池来对数据库进行操作了,操作的代码和普通的连接数据库差不多,只是需要在中间加两行代码。
java中普通连接mysql数据库是这样的:
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "root";
String sql = "select * from test";
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try
{
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next())
{
String user = rs.getString(1);
String pwd = rs.getString("pwd");
out.println(user + "\t" + pwd);
System.out.println(user + "\t" + pwd);
}
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
try
{
if (rs != null)
{
rs.close();
rs = null;
}
if (ps != null)
{
ps.close();
ps = null;
}
if (conn != null)
{
conn.close();
conn = null;
}
} catch (SQLException e)
{
// TODO: handle exception
e.printStackTrace();
}
}
而使用数据库连接池后是这样的:
String sql = "select * from test";
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try
{
Context context = new InitialContext();
DataSource ds = (DataSource) context.lookup("java:/comp/env/jdbc/mysql");
conn = ds.getConnection();
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next())
{
String user = rs.getString(1);
String pwd = rs.getString("pwd");
out.println(user + "\t" + pwd);
System.out.println(user + "\t" + pwd);
}
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
try
{
if (rs != null)
{
rs.close();
rs = null;
}
if (ps != null)
{
ps.close();
ps = null;
}
if (conn != null)
{
conn.close();
conn = null;
}
} catch (SQLException e)
{
// TODO: handle exception
e.printStackTrace();
}
}
和普通连数据库相比就从
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
改变为
Context context = new InitialContext();
DataSource ds = (DataSource) context.lookup("java:/comp/env/jdbc/mysql");
conn = ds.getConnection();
这里的jdbc/mysql
就是context.xml配置文件中Resource
标签中的name。
参考资料
[1] 开源数据库连接池之Tomcat内置连接池(http://www.cnblogs.com/fjdingsd/p/5273187.html)