Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect a SQL table's existence in Java?

Tags:

java

sql

database

How can I detect if a certain table exists in a given SQL database in Java?

like image 379
Bobby Avatar asked May 29 '09 19:05

Bobby


People also ask

How do I check if a table exists?

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 do you check if a table exists in a schema?

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.

How do I know which database is used in Java?

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.


1 Answers

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)); } 
like image 148
Ayman Hourieh Avatar answered Oct 11 '22 06:10

Ayman Hourieh