user5707315
user5707315

Reputation:

How to check if view exists in java?

DatabaseMetaData dbm = connection.getMetaData(); // connection is of type Connection (in JDBC)  
ResultSet tables = dbm.getTables(null, null, "table name", null); // check if table is there
if (tables.next()) {
    //Table exists
} else {
    //Table does not exist
}

My question is how to check if the view exists. The above code is how to check if the table exist. I know it is similar to the above code but I'm having trouble.

Upvotes: 2

Views: 1546

Answers (2)

Mark
Mark

Reputation: 1983

My issue was that table names were written in java code with camel case which caused an issue when checking if a table existed - but it worked fine with dropping and creating. So what I did was simply

ResultSet tables = dbm.getTables(null, null, "table name".toLowerCase(), null);

Upvotes: 0

Kayaman
Kayaman

Reputation: 73558

The getTables() method can return all types of tables (where a view is considered a type of a table). The last parameter can be used to search for specific type(s).

In your case you could use dbm.getTables(null, null, "viewname", new String[]{"VIEW"});. The javadocs explain this very well, so you should be reading them before you ask here.

Upvotes: 5

Related Questions