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

后端 未结 4 610
清酒与你
清酒与你 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 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;   
    

提交回复
热议问题