Reputation: 89
I have a list called tList
, which contains names of tables
of a database
. Tables in this list may or may not exist. I want to retrieve data from every table if it is present. I am doing it like this.
for(String t:tList){
sql=Select * from t
}
But in this scenario if table
is not present, I am getting exception that table is not present and my program gets terminate. How to handle this so that I can retrieve data only and only if that table is present
In one more scenario if table is present but it is empty than also I am getting error. Please help in these two scenarios
Upvotes: 1
Views: 266
Reputation: 4507
Have you tried DatabaseMetaData.getTables() Example:
DatabaseMetaData md = connection.getMetaData();
ResultSet rs = md.getTables(null, null, t, null); //t is your tableName (defined in loop of your question)
while (rs.next()) {
System.out.println(rs.getString(3));
}
Edit
To answer your empty table question:
//your query
sql=Select * from t
Statement stmt = yourDBConnection.createStatement();
ResultSet rs = stmt.executeQuery(sql);
if (!rs .isBeforeFirst() ) {
System.out.println("Table is empty");
}
Upvotes: 1
Reputation: 3673
I think the more appropriate way is to get data is java.sql.DataBaseMetaData.
A java.sql.Connection object is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on. This information is obtained with the getMetaData method.
Refer: https://docs.oracle.com/javase/7/docs/api/java/sql/Connection.html https://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html
Upvotes: 1