JDBC Examples Tutorials | Advance Java Examples Tutorials and more links and downloads

Sunday, February 8, 2009

Display All Tables Of Database

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

/**
* Connect to one database and display all its tables.
*
*
*/
public class JDBCTest5 {

// used for db connection
private static Connection conn;

// at loading of class, connects to DB
static {
// make connection with Employee Database
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

// connectivity 1 : Require DSN named : dsn
// conn = DriverManager.getConnection("jdbc:odbc:dsn" ,"","");

// connectivity 2 : No requirement of DSN, direct connectivity to
// input file name
String sDBQ = "D:\\emp.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ="
+ sDBQ + ";DriverID=22;READONLY=true";
conn = DriverManager.getConnection(database, "", "");
} catch (ClassNotFoundException cnfe) {
System.out.println("Class Not Found Exception");
cnfe.printStackTrace();
} catch (SQLException sqle) {
System.out.println("SQL Exception");
sqle.printStackTrace();
}
}

/**
* execution begins from here
*
* @param args
* command line arguments
*/
public static void main(String[] args) {
getEmpTableMetaData();
}

/**
* gets employees table data and display in good format
*
*/
public static void getEmpTableMetaData() {
try {

// statement to execute query
Statement stmtObj = conn.createStatement();

// Holds the Meta-Data
DatabaseMetaData dbmdObj = conn.getMetaData();

// Get the table names in the ResultSet object using the
// getTables(String catalog, String schemaPattern, String
// tableNamePattern, String[] types)
// method matching the catalog, schema, table name and type criteria
// specified.
// In this case all the tables are returned
ResultSet rsTables = dbmdObj.getTables(null, null, null, null);

// table found flag
boolean blFound=false;

// Iterate through the ResultSet object
System.out.println("Tables In DB Are :");
while (rsTables.next()) {
String tableName = rsTables.getString("TABLE_NAME");
String ttype = rsTables.getString("TABLE_TYPE");

// checks if it's a user-defined table
if (ttype.equals("TABLE"))
{
blFound=true;
System.out.println("\t" + tableName);
}
}

// if no table found
if(!blFound)
System.out.println("\n\tNo Table Found!!");

} catch (SQLException sqle) {
sqle.printStackTrace();
} finally {
conn = null;
}

}
}

No comments:

Post a Comment

Followers