In a desktop application with an embedded Derby database, what should I keep alive (as opposed to recreating each time when talking with the database) for the whole lifetime of the application?
ConnectionandStatement, using the same statement throughout the lifetime of the program?Connection, recreating statement repeatedly?- Neither of these. That is, recreating connection and statement repeatedly?
From a database amateur’s viewpoint it would seem reasonable to avoid recreating anything that doesn’t need to be recreated, but is option 1 (or 2) against standard practices or are there some obvious cons? Is (re)creating connections and statements expensive or not?
In an embedded Derby application, both Connection and Statement objects are quite cheap and I think you should not worry about creating them as you need them. In the Derby unit test suites, we create tens of thousands of connections and hundreds of thousands of statements, without problems.
It is also fine to keep your Connection and Statement objects around as long as you wish. Embedded Derby has no time limit, and will not drop the connection or statement objects unless you tell it to (by closing them), or unless you leak them away, in which case the Garbage Collector will clean them up (eventually).
Although it is fine to keep the connection around, you should commit() the transaction when it is complete (unless you run in autocommit mode of course).
And, if you are keeping a result set around, be aware that committing the transaction will usually also close the result set, less you specifically construct the special result sets that are held open across commit.