Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Answers Viewqa JDBC How to check whether database exists?

Have Programming Question? Ask it here!
 
 
 


Narayanan
How to check whether database exists?
1 Answer(s)      3 years and 5 months ago
Posted in : JDBC


Hi,

I have to create a database in mysql. I am able to create that successfully from using JDBC. But before to creating the database, i want to check whether database exists or not? How can i do this check. can any one help me on this.

Please find thesample code

`public class CreateDatabase {  public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
try {
  Class.forName("org.gjt.mm.mysql.Driver").newInstance();
  String url = "jdbc:mysql://localhost/mysql";
  connection = DriverManager.getConnection(url, "username", "password");

  statement = connection.createStatement();
  String hrappSQL = "CREATE DATABASE hrapp";
  statement.executeUpdate(hrappSQL);
} catch (Exception e) {
  e.printStackTrace();
} finally {
  if (statement != null) {
    try {
      statement.close();
    } catch (SQLException e) {
    } // nothing we can do
  }
  if (connection != null) {
    try {
      connection.close();
    } catch (SQLException e) {
    } // nothing we can do
  }
}

}

} `

Thanks, Narayan


Advertisement
View Answers

November 13, 2010 at 5:30 PM


Hi Friend,

You can use the following code:

import java.sql.*;
import java.util.*;
class CheckDatabase{
    public static void main(String[] args) throws Exception{
        ArrayList<String> list=new ArrayList<String>();
        Scanner input=new Scanner(System.in);
        System.out.println("Enter Database name:");
        String database = input.nextLine();
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306","root","root");
        Statement st = con.createStatement();
        DatabaseMetaData meta = con.getMetaData();
        ResultSet rs = meta.getCatalogs();
        while (rs.next()) {
            String listofDatabases=rs.getString("TABLE_CAT");
            list.add(listofDatabases);
        }
        if(list.contains(database)){
        System.out.println("Database already exists");
            }
            else{
            st.executeUpdate("CREATE DATABASE "+database);
            System.out.println("Database is created");
            }
            rs.close();
        }

    }

Thanks



Related Tutorials/Questions & Answers:
Advertisements
Advertisements
 

 

 

DMCA.com