JDBC: Listing Table names Example


 

JDBC: Listing Table names Example

In this section, we are describing how to list all table names of a database using JDBC API.

In this section, we are describing how to list all table names of a database using JDBC API.

JDBC: Listing Table names Example

In this section, we are describing how to list all table names of a database using JDBC API.

List Tables name in Database :

DatabaseMetaData is an interface, implemented by driver which helps user to know the capabilities of DBMS.
Some DatabaseMetaData methods gives you list of information to the ResultSet Objects.
Method getMetaData() contains metadata about the database and also contains information about the database's tables. So you can list all tables name by using method  getTables().

Following is the way to list the tables -
DatabaseMetaData md = con.getMetaData();
ResultSet rs =
md.getTables(null, null, "%", null);

Example :  In this example we are listing all the tables in the students databse.

package jdbc;

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

class GetTableName {
	public static void main(String[] args) {
		System.out.println("Get all tables name in JDBC...");
		Connection con = null;
		ResultSet rs = null;
		String url = "jdbc:mysql://localhost:3306/";
		String dbName = "students";
		String driverName = "com.mysql.jdbc.Driver";
		String userName = "root";
		String password = "root";
		try {
			Class.forName(driverName);

			// Connecting to the database
			con = DriverManager.getConnection(url + dbName, userName, password);
			try {

				// Getting all tables name
				DatabaseMetaData md = con.getMetaData();
				rs = md.getTables(null, null, "%", null);
				System.out.println("List of tables in database students -");
				while (rs.next()) {
					System.out.println(rs.getString(3));
				}
			} catch (SQLException e) {
				System.out.println(e);
			}
			con.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output :

Get all tables name in JDBC...
List of tables in database students -
course
student

Ads