Check if Database Exists using Java

We can check if database exists using java.sql.DatabaseMetaData interface. using DatabaseMetaData interface we can obtain the meta data about the database catalog, for example we can obtain the database name, tables available in that database, columns in that table etc.

The getCataLogs() method which is called on the instance of  DataBaseMetaData, retrieves the catalog name available in database and return a ResultSet object, the ResultSet object’s each row has a single String column that is a catalog name.

code to check if database exists using java:-

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


public class IsDbExist {

	public static void main(String[] args){

		Connection con = null;
		ResultSet rs = null;

		String url = "jdbc:mysql://localhost:3306/";
		String user = "root";
		String password = "";

		try{

			Class.forName("com.mysql.jdbc.Driver");

			con = DriverManager.getConnection(url, user, password);
			
			String dbName = "test";

			if(con != null){
				
				System.out.println("check if a database exists using java");

				rs = con.getMetaData().getCatalogs();

				while(rs.next()){
					String catalogs = rs.getString(1);
					
					if(dbName.equals(catalogs)){
						System.out.println("the database "+dbName+" exists");
					}
				}

			}
			else{
				System.out.println("unable to create database connection");
			}
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		finally{
			if( rs != null){
				try{
				    rs.close();
				}
				catch(SQLException ex){
					ex.printStackTrace();
				}
			}
			if( con != null){
				try{
				    con.close();
				}
				catch(SQLException ex){
					ex.printStackTrace();
				}
			}
		}
	}
}

output:-

check if database exists using java

the database test exists

The results are ordered by catalog name and if you don’t want to use rs.getString(1) the you can also write like this rs.getString(“TABLE_CAT”) to check if database exists using java. In the above code we are checking that a particular database exists or not now if you wan to get the list of database catalogs, you can simply print the rs.getString(1) value.

Leave a Comment