The Beauty of Java Hashtable (Old, 2010)

Sometimes newbies can’t quite grasp how to use Java to get data from a database in an easy way.
A simple hashtable goes a long way in web development. for instance:

String sql = “select name,age,dob from employee”;

//notice the use of String key and Object value, since data from the database comes in many forms:Decimal,varchar,boolean
Hashtable<String,Object><string,object><string,object><string,object> employees = new Hashtable<string,object><string,object><string,object><String,Object><string,object>();

int count 0;

ResultSet rs = statement.executeQuery();
while(rs.next()){

employees.put(“name”+count,rs.getString(“name”));
employees.put(“age”+count,rs.getString(“age”));
employees.put(“dob”+count,rs.getString(“dob”));
count++;
}
This simple routine will give the novice developer a new weapon to his her arsenal.
Here we have a generic way store database data in an array.
If the data was all varchar, which is Java String, we could have created a hashtable with a signature of <String,String><string,string>. However, <String,Object>String,Object> gives the flexibility we need.

Don’t forget to increment that counter!

Advertisements

Author: Michael Clayton

Technologist, Developer, Music Technology

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s