Retrieve Database Table Names


import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.HashSet;
import java.util.Set;

public class TableNames {

public static void main(String[] args) {
	Connection conn = null;
	try {
		conn = getConnection();
		Object tableNames[] = getTableNames(conn).toArray();
		for (int i=0; i<tableNames.length; i++) {
			System.out.println(tableNames[i]);
		}
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		try {
			if (conn!=null) {
				conn.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

public static Connection getConnection() throws Exception {

	Connection conn = null;
	String driverName = "org.hsqldb.jdbcDriver";
	String databaseUrl = "jdbc:hsqldb:hsql://mymachine:9001/mydatabase";
	String user = "username";
	String pwd = "password";
	Driver driver = (Driver) Class.forName(driverName).newInstance();
	DriverManager.registerDriver(driver);
	conn = DriverManager.getConnection(databaseUrl, user, pwd);
	return conn;
}

public static Set<String> getTableNames(Connection conn) throws Exception
{
	Set<String> tableNames = new HashSet<String>();
	DatabaseMetaData dbMetaData = conn.getMetaData();
	ResultSet resultSet = null;
	try
	{
		resultSet = dbMetaData.getTables(null, getDefualtSchemaName(conn), "%", new String [] { "TABLE" });
		if(resultSet != null)
		{
			while(resultSet.next())
			{
				String tableName = resultSet.getString("TABLE_NAME");
				tableNames.add(tableName);
			}
		}
	}
	finally
	{
		if(resultSet != null)
		{
			resultSet.close();
		}
	}
	return tableNames;
}

public static String getDefualtSchemaName(Connection conn) {
	String defualtSchemaName = "public";
	try {
		DatabaseMetaData dbMetaData = conn.getMetaData();
		String url = dbMetaData.getURL();
		if (url.startsWith("jdbc:hsqldb")) {
			defualtSchemaName = "PUBLIC";
		} else if (url.startsWith("jdbc:postgresql")) {
			defualtSchemaName = "public";
		} else if (url.startsWith("jdbc:oracle")) {
			defualtSchemaName = "public";
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return defualtSchemaName;
}

}

You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

AddThis Social Bookmark Button

Similar Posts

Comments are closed.