Finally block and close methods
[nobr]In my Tomcat 4.1.27 container I am trying to get thefinally block to work where it closes the MySQL database connection.Here is my attempt which will not compile:
package packone;
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
publicclass Datafetchextends HttpServlet{
Connection connection =null;
Statement stmt =null;
ResultSet results =null;
publicvoid doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try
{
Class.forName("org.gjt.mm.mysql.Driver");
String dbURL ="jdbc:mysql://localhost/dbone";
String username ="jones";
String password ="a123rd";
connection = DriverManager.getConnection(dbURL, username, password);
stmt = connection.createStatement();
results = stmt.executeQuery("SELECT * from teamone");
while(results.next())
{
String lastname = results.getString("lastname");
out.write(lastname +"<br>");
}
}
catch(ClassNotFoundException e){
System.out.println("Database driver not found.");
}
catch(SQLException e){
System.out.println("Error opening the db connection: " + e.getMessage());
}
finally
{
results.close();
stmt.close();
connection.close();
}
}
}
The error messages after I try and compileDatafetch.java:
packone\Datafetch.java:47: unreported exception java.sql.SQLException; must be caught or declared to be thrown
results.close();
^
packone\Datafetch.java:48: unreported exception java.sql.SQLException; must be caught or declared to be thrown
stmt.close();
^
packone\Datafetch.java:49: unreported exception java.sql.SQLException; must be caught or declared to be thrown
connection.close();
^
3 errors
If I take out the finally block the Sevlet compiles and shows data in the web page.
Please advise how I can get the finally block to work with the Database close methods.[/nobr]

