Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Creating method for ResultSet statement

Status
Not open for further replies.

chicago1985

Technical User
Oct 11, 2007
10
US
I have a repeated resultset object that I use alot to execute a statement that fetches max id from a table.

I was wondering if I can put it in a method and call the method each time I need the max id?

The repeated part is:
Resultset rs = statement.executeQuery("select max(id) from TableMain");
rs.next();


Here is an example of what I am doing now:
Code:
Statement statement = connection.createStatement();
if(condition here..)
{
    Resultset rs = statement.executeQuery("select max(id) from TableMain");
    rs.next();
    a = rs.getInt(1);
    //my insert sql is here to insert into another table the value of the max id....

//another call to get the max id:
if(another condition here...)
{
    Resultset rs = statement.executeQuery("select max(id) from TableMain");
    rs.next();
    c = rs.getInt(1);
   //my insert sql is here to insert into another table the value of the max id....

I need help on my attempt below because I am not sure how to do it:
Code:
public ResultSet getMaxId()
{
         Resultset rs = statement.executeQuery("select max(id) from TableMain");
         rs.next();
         return rs;
}

Call it like this:
Code:
if(any condition here..)
{
    getMaxId();
    f = rs.getInt(1);
   ///my insert sql is here to insert into another table the value of the max id....
 
The name is already showing the way, go one step forward, and return the id, not the ResultSet:
Code:
 private int getMaxId ()
{
         Resultset rs = statement.executeQuery ("select max(id) from TableMain");
         rs.next();
         return rs.getInt (1);
}

void foo  ()
{
	// ...
	if(any condition here..)
	{
		int f = rs.getMaxId
		// ...
Since Statement isn't designed in the scope of the method getMaxId, I guess it's a better idea to make it private.
Inside your class, you may be careful, and avoid a statement being null, a connection being closed.
From outside, it's hard to do.

Unknown autor: "Public interfaces are forever."

don't visit my homepage:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top