我正在构建一个 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 block 中使用的结果集和语句。参见 http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html#Random_Connection_Closed_Exceptions一个更完整的例子。
关于jsp - 如何在 Tomcat 6 和 MySQL 中使用连接池?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4728654/