Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to return a ResultSet

Tags:

java

mysql

I'm new to java but I'm picking it up pretty quickly. One thing that I keep running into is I end up having one function that is full of queries and just code in general and I would like to break it down into separate functions. Take this for example:

public ResultSet getApples (){
    ResultSet rs;
    try{
        PreparedStatement stmt = con.prepareStatement("SELECT * FROM fruit WHERE type='apples'");
        rs = stmt.executeQuery();
    } catch (SQLException e){
        e.printStackTrace();
    }
    return rs;  
}

Ideally this would be what I want to do, have all of try's and catches within one function, but this gives me the error: Local variable may not have been initilized

I do realize I could do this:


public function start(){
    try{
        ResultSet apples = getApples();
    catch (SQLException e){
        e.printStackTrace();
    }
}

public ResultSet getApples () throws SQLException { 
    PreparedStatement stmt = con.prepareStatement("SELECT * FROM fruit WHERE type='apples'");
    return stmt.executeQuery();
}

But I would really rather have the exceptions handled within the function as well as it return a result.

EDIT Alright so kinda a modififed answer to whats being provided. My whole goal on this question was to make the main functions of my script as clean as possible. Even the extra if ( _resultSet != null ) was something that I didn't really like. That being said I am pretty happy with this result:

public ResultSet getApples (){
    try{
        PreparedStatement stmt = con.prepareStatement("SELECT * FROM fruit WHERE type='apples'");
        return stmt.executeQuery();
    } catch (SQLException e){
        System.out.println("************************");
        System.out.println("Class.getApples null");
        System.out.println(e.getMessage());
        return null;
    }   
}

Everything is handled within the getApples function and when _resultSet.next() is called I get a NullPointerException and the prints in the getApples exception so I am able to find the error and debug quickly.

like image 423
locrizak Avatar asked Aug 10 '12 12:08

locrizak


2 Answers

Initialize rs to null first.

public ResultSet getApples (){
    ResultSet rs = null;
    try{
        PreparedStatement stmt = con.prepareStatement("SELECT * FROM fruit WHERE type='apples'");
        rs = stmt.executeQuery();
    } catch (SQLException e){
        e.printStackTrace();
    }
    return rs;  
}
like image 108
evg Avatar answered Oct 04 '22 00:10

evg


You can declare your RS like this

ResultSet rs = null;

but where you call your function:

ResultSet apples = getApples ()

you have to check:

if(apples == null)
{
    //do something, because your query did not work.
}
like image 29
John Smith Avatar answered Oct 04 '22 00:10

John Smith