PostUsing the ArrayList object in JAVA

I continue sharing with you bits of code from my JAVA project picking up the thread left in Running SQL queries in JAVA. I remind you that I must develop a library application for school project.

So far I showed you how I connected to a database and how I manipulate data from that database. In the interface I use scrolled combo boxes (JComboBox object) and scrolled lists (JList). This wouldn’t present a problem except these objects accept arrays. Because in my database I have a dynamic number of records and  I don’t know the exact number of rows of a query result I can’t use arrays. Instead I use the ArrayList object which allows me to create an array with an unknown number of items.

I will show you how I used this object below.

private ArrayList listaAutori() {
 ArrayList rawAutori = new ArrayList();
 try {
  String query = "SELECT id_autor, nume, prenume FROM AUTOR";
  ResultSet rs = st.executeQuery (query);
  while (rs.next ()) {
   int id_autor = rs.getInt("id_autor");
   String rawNume = rs.getString("nume");
   String rawPrenume = rs.getString("prenume");
   String nume = String.format("%s%s",Character.toUpperCase(rawNume.charAt(0)),
                                        rawNume.substring(1));
   String prenume = String.format("%s%s",
                                   Character.toUpperCase(rawPrenume.charAt(0)),
                                        rawPrenume.substring(1));
   rawAutori.add(id_autor + ": " + nume + " " + prenume);
  }
 } catch (SQLException sqlex) {
  JOptionPane.showMessageDialog (this, sqlex);
 }
 return rawAutori;
}

The result of this function is then transformed to array using the following call

listaAutori().toArray();

It’s no too complicated but very helpful. Hope you find this useful.

I Disclose

Stay Connected

Subscribe to RSS Feed

Subscribe to RSS Feed

Follow me on Twitter

Follow me on Twitter

Subscribe via e-mail

Subscribe via e-mail


Post your comment

Leave a Reply