Skip to content
Advertisement

Returning ResultSet without close?

I would like to have a database connection managing class which I can use for simple SQL commands like SELECT, INSERT etc. by simple calling something like this (class below):

ResultSet test = DataService.getResultSet("SELECT NOW()");
test.first();
System.out.println(test.getString(1));

This is class I’ve found on web:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Database object to load drivers and perform queries
 * @author Abdulsalam Umar blog.salamtura.com
 */
public class DataService {

    private static Connection con;
    private static final String Driver = "oracle.jdbc.driver.OracleDriver";
    private static final String ConnectionString = "Your database connection string";
    private static final String user = "username";
    private static final String pwd = "password";

    /**
     * create Database object
     */
    public DataService() {
    }

    /**
     * to load the database base driver
     * @return a database connection
     * @throws SQLException throws an exception if an error occurs
     */
    public static Connection loadDriver() throws SQLException {
        try {
            Class.forName(Driver);
        } catch (ClassNotFoundException ex) {
            System.out.println(ex.getMessage());
        }
        con = DriverManager.getConnection(ConnectionString, user, pwd);
        return con;
    }

    /**
     * to get a result set of a query
     * @param query custom query
     * @return a result set of custom query
     * @throws SQLException throws an exception if an error occurs
     */
    public static ResultSet getResultSet(String query) throws SQLException {
        Connection con = loadDriver();
        ResultSet rs;
        PreparedStatement st = con.prepareStatement(query);
        rs = st.executeQuery();

        return rs;
    }

    /**
     * to run an update query such as update, delete
     * @param query custom query
     * @throws SQLException throws an exception if an error occurs
     */
    public static void runQuery(String query) throws SQLException {
        Connection con = loadDriver();
        ResultSet rs;
        PreparedStatement st = con.prepareStatement(query);
        st.executeUpdate();
    }
}

Is this way of returning ResultSet without closing it (and closing the statement) right? How can I return the ResultSet from the method?

Advertisement

Answer

Returning result set is not a good idea. So,fetch the required data and make use of collection to return the data. This answer may be useful

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement