Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java code to check if a given User, Schema, Table exists?

I want to make Java code (using Oracle 11g and JDBC also) which will check if a particular User or Schema exists or not. How can I do this by using only Java code and not by executing SQL queries (inside my java code) to do the checking ?

Thanks.

EDIT -

METHOD 1:

In MySQL, we can use something like this -

Connection conn = DriverManager.getConnection(url,username,password);
DatabaseMetaData DMD = conn.getMetaData();
ResultSet res = DMD.getCatalogs();
 while (res.next()) {
      String database = res.getString("TABLE_CAT");
}

Now put an if inside the while to check it given DB exists.

METHOD 2:

OR, you can execute some queries like mentioned in this post. Using SQL query to determine if a table exists

I want to use something like method 1 to do the job instead of method 2 - That is what i meant.

like image 846
sweet dreams Avatar asked Jun 30 '26 17:06

sweet dreams


1 Answers

The pure JDBC way to interrogate the database about this sort of thing is to use the DatabaseMetaData class in your Java application. DatabaseMetaData.getSchemas will give you the set of schemas in the database. DatabaseMetaData.getTables will give you a listing of the tables. You can write code that iterates through these ResultSet objects to see if a particular table or schema exists.

Of course, behind the scenes, the JDBC driver is simply executing SQL queries against the Oracle data dictionary to get this information.

like image 193
Justin Cave Avatar answered Jul 02 '26 06:07

Justin Cave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!