How to check if a particular database in mysql already exists using java

后端 未结 4 587
清酒与你
清酒与你 2020-12-09 11:00

I am new in JDBC and I wanted to find out if there is a way to check if a particular database already exists in MySQL.

Let\'s say I wanted to create a database named

相关标签:
4条回答
  • 2020-12-09 11:40
    show databases like 'students'
    

    If you get a row back, it exists.

    0 讨论(0)
  • 2020-12-09 11:40

    You're doing it back to front. The correct technique is to try to create it and catch the exception. The way you want to do it is subject to timing-window problems: it wasn't there when you tested, but it was there when you tried to create it. And you still have to catch the exception anyway.

    0 讨论(0)
  • 2020-12-09 11:44

    You can get that info from a JDBC Connection using DatabaseMetaData#getCatalogs, here is an example of getting the Catalogs, aka Database names

    // Connection connection = <your java.sql.Connection>
    ResultSet resultSet = connection.getMetaData().getCatalogs();
    
    //iterate each catalog in the ResultSet
    while (resultSet.next()) {
      // Get the database name, which is at position 1
      String databaseName = resultSet.getString(1);
    }
    resultSet.close();
    
    0 讨论(0)
  • 2020-12-09 12:01

    In newer versions of MySQL (5 and above) run this query:

    SELECT COUNT(*)
    FROM information_schema.tables 
    WHERE table_schema = '[database name]' 
    AND table_name = '[table name]';
    

    If the result is 1 it exists.

    In Java JDBC that would look something like this:

    // Create connection and statement
    String query = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema'[database name]' AND table_name = '[table name]'";
    ResultSet rs = stmt.executeQuery(query);                  
    rs.next();
    boolean exists = rs.getInt("COUNT(*)") > 0;
    // Close connection, statement, and result set.
    return exists;   
    
    0 讨论(0)
提交回复
热议问题