我正在构建一个 Web 应用程序,我想使用“连接池”,因为它带来了好处。我阅读了一些教程,但我真的不明白我需要做什么。
如果有人能给我一个北方,我很感激。
我正在使用 JSP/Servlet、MySQL、Tomcat 6 和 Netbeans 6.9.1。
最好的问候,瓦尔特·恩里克。
我正在构建一个 Web 应用程序,我想使用“连接池”,因为它带来了好处。我阅读了一些教程,但我真的不明白我需要做什么。
如果有人能给我一个北方,我很感激。
我正在使用 JSP/Servlet、MySQL、Tomcat 6 和 Netbeans 6.9.1。
最好的问候,瓦尔特·恩里克。
你读过http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html#MySQL_DBCP_Example吗?它向您展示了从 Web 应用程序访问数据库的所有步骤。
如果您需要使用 Java 代码(比 JSP 好得多)访问数据库,您的代码应如下所示:
InitialContext initCtx = new InitialContext();
// getting the datasource declared in web.xml
DataSource dataSource = (DataSource) initCtx.lookup("java:comp/env/jdbc/TestDB");
// getting a connection from the dataSOurce/connection pool
Connection c = null;
try {
c = dataSource.getConnection();
// use c to get some data
}
finally {
// always close the connection in a finally block in order to give it back to the pool
if (c != null) {
try {
c.close();
}
catch (SQLException e) {
// not much to do except perhaps log the exception
}
}
}
另外,请注意,您还应该关闭 try 块中使用的结果集和语句。有关更完整的示例,请参阅http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html#Random_Connection_Closed_Exceptions 。