You could of course port this over to Java instead but if the database is not up to scratch as in indexed properly you'll still end up getting timeouts or exceptions.

It might be worth while...