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
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
Ads