In part 4 of this series, we began creating a class that would handle all of our database needs. We created a constructor and our database Connection object, and are now ready to write the functions to query our database.
There are two different functions which we need to write in order to maximize our functionality. One function will use executeUpdate() and the other will use executeQuery() and return a ResultSet to the calling program. The first is simple, as we only need to run the update. Neither of these functions will handle errors, but instead throw any exceptions back to the calling program.
public void sendUpdate(String query) throws SQLException
{
stat.executeUpdate(query);
}
You can choose to return the number of lines the query affected by using this function instead.
public int sendUpdate(String query) throws SQLException
{
int numAffected = stat.executeUpdate(query);
return numAffected;
}
The next function is very similar to the previous one.
public ResultSet sendQuery(String query) throws SQLException
{
stat.executeQuery(query);
ResultSet result = stat.getResultSet();
return result;
}
Now the only thing left to do is to close our connections when we are finished with this class. This could be done with a separate function that the calling program would need to run, but I think using a destructor is a more graceful solution.
@Override
protected void finalize()
{
try {
stat.close();
mysqlConn.close();
super.finalize();
} catch (SQLException e) {
System.err.println("Error code: " + e.getErrorCode());
System.err.println("Error message: " + e.getMessage());
} catch (Throwable e) {
System.err.println(e);
}
}
That’s all there is to it. Now you have all the tools at your disposal to create a database connection within your java programs and utilize it to grow your software production to greater heights. Information on downloading and installing the JDBC can be found at mysql.com and more information about using JDBC can be found in the documentation found on the java.sun.com website.