小编典典
如果您需要使用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。
2020-06-10