• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem in Seperating Core Servlet to Database Query Java

 
Ken Shamrock
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to seperate database query function(like get a resultset) from my servlets, so I will need to make a database.java contains following code(to return a ResultSet to my servlet):
private ResultSet userquery(String driverName,String connectionURL,String query,java.io.PrintWriter out,String a,String uri)
{
Connection con = null; // JDBC Connection
Statement stmt = null; // JDBC Statement
ResultSet rs = null; // JDBC ResultSet


try {
Class.forName(driverName).newInstance();
con = DriverManager.getConnection(connectionURL);

stmt = con.createStatement();
// Execute the query
rs = stmt.executeQuery(query);
return rs;
}
catch (Exception ex) {
// Send the error back to the client
out.println("Exception!");
ex.printStackTrace(out);
rc = false;
}
finally {
try {
// Always close properly
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (con != null) {
con.close();
}
}
catch (Exception ex) {
// Ignore any errors here
}
}
}
My servlet will create this database object and call this method eg:
Database database=new database();
userquery(driverName,connectionURL,"Select * from table",...)
But it seems conflicts and database.java can't return a resultset to my servlet as it will close resultset (rs.close) before it leave. How can I rearrage and make it works? Thanks very mucj
 
Michael Yuan
author
Ranch Hand
Posts: 1427
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you do not want database code in your servlet, you probablly do not want the servlet to process resultset. In the "database" object, you should parse the resultset into a Vector and return the "business information" back to the servlet.
Or, you can use JavaBeans to replace the "database" object and provide meaningful data access API to your database tables.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic