Java database wrapper

I have never liked to code in Java, it just feels so verbose, so uncreative, so boring.
It's hard to create anything smart. But sometimes it's possible :)

Today I have been working with database access in Java. The API is very powerful, but kind of verbose.

Here is a standard way to execute a simple query:

String sql = "SELECT metadata FROM mailbox WHERE mailbox_id = ? AND section = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, 1);
stmt.setString(2, "Fluffy");
ResultSet rs = stmt.executeQuery();

This is all right, but it can be shorter:

String sql = "SELECT metadata FROM mailbox WHERE mailbox_id = ? AND section = ?";
Object[] va = {1, "Fluffy"};
ResultSet rs = AmiDb.executeQuery(sql, va);

executeQuery is implemented like this:

PreparedStatement stm = getStatement(sql);
int i = 1;
for(Object obj : variables) {
    stm.setObject(i, obj);
    i++;
}
return stm.executeQuery();

Off topic: I miss Python dictionaries in Java!

Sun should add syntactic sugar for HashMaps - it would make HashMaps a lot more useful.

For example, instead of typing this:

HashMap<Object, Object> vars = new HashMap<Object, Object>();
vars.put(1, "Fluffy");
vars.put(2, "Ferret");
my_obj.methodCall(vars);

One could type this:

my_obj.methodCall({1: "Fluffy", 2: "Ferret"});

This addition would open up for a new realm of extensions :)

Code · Tips 4. Apr 2007
© Amir Salihefendic. Powered by Skeletonz.