problem with closing connection on db with servlet
I am trying to run my app with tomcat an the first time that I am debugging/running the app its work fine. but when I am trying to run on second time I am getting error "XJ040".
"Failed to start database 'C:\Documents and Settings\vitaly87\.netbeans- derby\articals' with class loader WebappClassLoader
context: /WebApplication1
delegate: false
repositories:
I thinks the problem because something wrong with closing the connections.Because when I stop my server the problem goes away until the second run.
here the code:
private Connection connect = null;
//private Statement stmt = null;
private PreparedStatement pre开发者_如何学PythonparedStatement = null;
private ResultSet resultSet = null;
public ArrayList<story> stories=new ArrayList<story>();
void getStories(String version) throws SQLException{
try{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
}catch(ClassNotFoundException e){
System.out.println(e);
}
connect = DriverManager.getConnection( "jdbc:derby:C:\\Documents and Settings\\vitaly87\\.netbeans-derby\\articals", "admin", "admin");
// statement = connect.createStatement();
int ArticlesId= Integer.parseInt(version);
preparedStatement = connect.prepareStatement("SELECT * FROM admin.articles where id>"+ArticlesId+"");
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
stories.add(new story(resultSet.getString("title"),resultSet.getString("date"),resultSet.getString("text")));
}
close();
}
//close connection
private void close() {
try {
if (resultSet != null) {
resultSet.close();
}
if (connect != null) {
connect.close();
}
} catch (Exception e) {
}
thanks for helping
Best always close connections in a finally
connect = DriverManager.getConnection(...)
try
{
// use connection
}
finally
{
try
{
connect.close()
}
catch (SQLException e)
{
// log e
}
}
In your code the connection will not be closed if you have an exception for example in parseInt(version) or exequteQuery()
also in your case I don't think closing of result set is necessary because you are closing the connection anyway.
try {
if (resultSet != null) {
resultSet.close();
}
if (connect != null) {
connect.close();
}
} catch (Exception e) {
}
is problematic because 1. if resultSet.close() throws an exception the connection is never closed and 2. you won't see any exceptions thrown in this method. I'd recommend to at least log the catched exceptions.
精彩评论