JDBC: List of Database "schema" Name


 

JDBC: List of Database "schema" Name

In this section, we are describing how to list database 'schema' names using JDBC API.

In this section, we are describing how to list database 'schema' names using JDBC API.

JDBC:  List of Database "schema" Name

In this section, we are describing how to list database 'schema' names using JDBC API.

List of 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.
In MySQL we use getCatalogs() method to retrieve the schema of database. The results are ordered by catalog name.

Example :

In this example we are listing the database schema names by using getCatalogs() method.

package jdbc;

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

class GetSchema{
	public static void main(String[] args) {
		System.out.println("Get database schema 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 {

				// Listing Database Schema names
				DatabaseMetaData md = con.getMetaData();
				rs = md.getCatalogs();
				System.out.println("List of database -");
				while (rs.next()) {
					System.out.println(rs.getString(1));
				}
			} catch (SQLException e) {
				System.out.println(e);
			}
			con.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output :

Get database schema name in JDBC...
List of database -
information_schema
jdbc
jdbc_example
mysql
students
test

Ads