简体   繁体   中英

Populate Array from Oracle Database

I am trying to create this from a DB Connection and populate the Array with the results. I just need help with populating "DestinationItem[]" from the SQL below.

//DestinationBean.java
//  Manual Array works but I need this to be populated from DB using the below Query and DB Connection info.
    private DestinationItem[] destinationResults = new DestinationItem[]{
            new DestinationItem("58285", "Dodge Grand Caravan"),
            new DestinationItem("57605", "Dodge SX 2.0"),
            new DestinationItem("58265", "Chrysler 300 Touring")
    };

    public DestinationItem[] getdestinationResults() {
        return destinationResults;
    }

    public class DestinationItem {
        String destid;
        String commdefid;

        public DestinationItem(String destid, String commdefid) {
            this.destid = destid;
            this.commdefid = commdefid;
        }
// Getter/Setter below

// END

I need to take this DB Connection Logic and populate the "DestinationItem[]" Array above and I need help.

//DBConnection
public static ArrayList<CustomerBean> getCustomer() {
    try {
        Class.forName("oracle.jdbc.OracleDriver").newInstance();

        Connection con = DriverManager.getConnection("jdbc:oracle:thin:", "BLAH", "BLAH");
        PreparedStatement ps = con.prepareStatement("select destination_id, commdef_id from BLAH.destination");

        ArrayList<CustomerBean> al = new ArrayList<CustomerBean>();

        ResultSet rs = ps.executeQuery();

        boolean found = false;

        while (rs.next()) {
            CustomerBean e = new CustomerBean();
            e.setDestId(rs.getString("destination_id"));
            e.setDestId(rs.getString("commdef_id"));
            al.add(e);
            found = true;
        }

        rs.close();
        if (found) {
            return al;
        } else {
            return null; // no entires found
        }
    } catch (Exception e) {
        System.out.println("Error In getCustomer() -->" + .getMessage());
        return (null);
    }
}

Here's a snippet that should do what you need:

List<DestinationItem> destinationsList = new ArrayList<DestinationItem>();

while (rs.next()) {
    destinationsList.add(new DestinationItem(
        rs.getString("destination_id"), rs.getString("commdef_id")));
}
rs.close();

// if you need to convert the list into an array, you can do it like this:
DestinationItem[] destinationsArray = destinationsList.toArray(
                                          new DestinationItem[destinationsList.size()]);

Some considerations:

It is easiest to use a dynamic data structure such as a List for retrieving data from the ResultSet , because that way you don't need to care about the number of rows returned from the DB before the iteration.

It is considered a best practise to never return null from methods that return List s (like your getCustomer() method). If no data is found, simply return an empty List . This will make client code simpler when null checks are not needed.

You should close the Connection con and PreparedStatement ps resources you open in the method. A common idiom for this is to have a structure like this in data-accessing methods:

Connection con = null;
PreparedStatement ps = null;
try {
    // initialize and use 'con' and 'ps'
} finally {
    if (ps != null) {
        ps.close();
    }
    if (con != null) {
        con.close();
    }
}

If you are on Java 7 or above, you can do the same in a more elegant way with the try-with-resources statement .

Finally, instead of catch (Exception e) , you should consider either throwing a possible (checked) SQLException from the method, or if you do not want to change the method signature, wrapping the SQLException into a RuntimeException . In general, you should not catch Exception s you cannot (or do not) handle in your method. In these cases, it's better to let the problem bubble up to the client code instead of silently ignoring it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM