Home Tutorial Java Core JDBC: List of Database "schema" Name

 
 

Share on Google+Share on Google+
JDBC: List of Database "schema" Name
Posted on: September 26, 2012 at 12:00 AM
Advertisement
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
Advertisement

Related Tags for JDBC: List of Database "schema" Name :


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: September 26, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com