Saturday, February 7, 2009

Get All table names from a mysql and oracle schemas using java

ResultSet resultSet = null;
ResultSetMetaData resultSetMetaData = null;
PreparedStatement preparedStatement = null;
Connection connection = null;
String sql = "";
Statement statement = null;
String oracleSql = "select object_name from user_objects where object_type = 'TABLE'";

try{

//for mysql
if(properties.getProperty("jdbc.identfier").toString().equalsIgnoreCase("MYSQL")){
DatabaseMetaData dbm = connection.getMetaData();
String[] types = {"TABLE"};
ResultSet rs = dbm.getTables(null,null,"%",types);
while (rs.next()){
String table = rs.getString(3) ;//table name
sql = "SELECT * FROM `"+table+"` limit 1 " ;
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
ResultSetMetaData metaData = resultSet.getMetaData();
for(int i=1 ; i<=metaData.getColumnCount();i++){
System.out.println(metaData.getColumnName(i));//column name
System.out.println((metaData.getColumnTypeName(i)); //column type
System.out.println((metaData.getColumnDisplaySize(i)); //size

}

}
}
//for oracle
else {
preparedStatement = connection.prepareStatement(oracleSql);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()){
String table = rs.getString(1) ;
tableVO.setTableName(table);
sql = "SELECT * FROM "+table+" where rownum<=1 " ;
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
ResultSetMetaData metaData = resultSet.getMetaData();
for(int i=1 ; i<=metaData.getColumnCount();i++){
System.out.println(metaData.getColumnName(i));//column name
System.out.println((metaData.getColumnTypeName(i)); //column type
System.out.println((metaData.getColumnDisplaySize(i)); //size

}


}
}

}
catch (Exception e) {
logger.error("error:"+e);
}
finally{ //close all objects
closeAll(resultSetMetaData,resultSet,statement,preparedStatement,connection);
}

1 comment:

Anonymous said...

good post.
thankssssssss.