Check for database availability
One solution is to add "; ifexists = true" to the database URL and try to open the database this way. If the database does not exist, you will get an exception. This works for HSQLDB and H2 database. For Apache Derby, add "; create = false" (in fact, just make sure there is no "; create = true"). "; Create = false" also works for the H2 database, but not for HSQLDB (it is simply ignored there). The disadvantage of this "ifexists = true" / "; create = false" trick is this: you will use exception handling to control application flow, which should be avoided (not only because throwing exception is slow). In addition, you will open a connection that you might not need. Update: HSQLDB 2.x seems to print a stack trace to System.err (!), If the database does not exist and you use "; ifexists = true", in addition to throwing an exception.
You can check if the database file exists. The disadvantage is that it depends on how the URL of the database is mapped to a file name, which depends on the internal elements of the database, such as the type of database and version of the database (!) And, possibly, on the properties of the system. For Derby, you need to check if the directory exists, as well as for some file, for example "service.properties" (it seems). For HSQLDB, you can check if the databaseName.properties file exists. For H2, check the databaseName.h2.db file. This is with current versions of Derby / HSQLDB / H2 and may change in the future.
The question, of course: why do you need to know if a database exists?
Check for circuit availability
Perhaps you really do not want to check for a database. Instead, you only need to check if a given schema exists in the database. For this you can use
SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '<SCHEMA NAME>'
This works both for HSQLDB (since version 2.x) and for H2. It also works with other databases. One exception is Derby, which does not support the standardized INFORMATION_SCHEMA schema.
Thomas mueller
source share