Bridges and databases – don’t let me near either

If you’re familiar with Calvin and Hobbes, you may recall the strip where Calvin asks his father how they determine the maximum load for bridges.

“Oh, they just drive larger and larger trucks over a bridge until it breaks, and take the weight of the last truck. Then they rebuild the bridge.”

It’s quite funny, until you realize that in a roundabout way, this is exactly what engineers do. Engineers learn how to build the next one from the last one.

So why should the Civil engineers have all the fun? Today I thought about how you can tell whether or not your Java String object is sitting on top of a VARCHAR2(10) database column or a VARCHAR2(15) column.

public void dynamicallyFindColumnLength() {
String lengthTester = new String(“”);
int length = 0;
try{
while(true){
lengthTester = lengthTester.concat(“X”);
//DB INSERT CODE GOES HERE

length++;
}
} catch (Exception e) {
//string too long
}
return length;
}

Simple, really. For those of you who are convinced that this code is awful and inefficient, I completely agree. I really should fix the method to double the length of the string on each iteration, and on an exception, perform a binary search between the last successful test and the exception. For long columns it should go quite a bit more quickly.

Alternatively you can annotate your String and reflectively retrieve the length. But that just doesn’t feel the same, does it?

This entry was posted in technical and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>