How can I detect if a certain table exists in a given SQL database in Java?
To check if table exists in a database you need to use a Select statement on the information schema TABLES or you can use the metadata function OBJECT_ID(). The INFORMATION_SCHEMA. TABLES returns one row for each table in the current database.
How to check whether a table (or view) exists, and the current user has access to it? SELECT EXISTS ( SELECT FROM information_schema. tables WHERE table_schema = 'schema_name' AND table_name = 'table_name' ); The information schema is mainly useful to stay portable across major versions and across different RDBMS.
If you have java. sql. Connection class, getMetaData method will return database information. From DatabaseMetaData object you can retrieve all kinds of stuff, like driver name or connection url, to determine your kind of server.
You can use DatabaseMetaData.getTables() to get information about existing tables.
This method works transparently and is independent of the database engine. I think it queries information schema tables behind the scenes.
Edit:
Here is an example that prints all existing table names.
DatabaseMetaData md = connection.getMetaData(); ResultSet rs = md.getTables(null, null, "%", null); while (rs.next()) { System.out.println(rs.getString(3)); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With