如何使用java检查mysql中的特定数据库是否已经存在

如何使用java检查mysql中的特定数据库是否已经存在

本文介绍了如何使用java检查mysql中的特定数据库是否已经存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 JDBC 新手,我想知道是否有办法检查特定数据库是否已存在于 MySQL 中.

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.

假设我想创建一个名为students 的数据库,如果已经在MySQL 中创建了students 数据库,则eclipse 中的错误消息将指出该students 数据库已经存在.但是我想做的是创建一个布尔方法来检查学生数据库是否已经存在.如果它存在,那么布尔方法将返回 false 否则它是 true 那么我可以创建学生数据库.我如何在 Java 中执行这些操作?JDBC 中是否有任何方法可以执行此操作,还是我需要从头开始编写代码?

Let's say I wanted to create a database named students, if the students database is already created in MySQL an error message in eclipse would state that this students database already exists. However what I wanted to do is to create a boolean method to check if students database already exists. If it exists then boolean method would return false otherwise its true then I can create students database.How do I do these in Java? Are there any methods in JDBC that does this or do I need to code it from scratch?

我遵循了 mguymons 的建议,这就是我想出来的

I followed mguymons suggestion and this is what I came up

public boolean checkDBExists(String dbName){

    try {
        Class.forName(JDBCDriver); //Register JDBC Driver

        System.out.println("Creating a connection...");
        conn = DriverManager.getConnection(DBURL, USER, PASS); //Open a connection

        ResultSet resultSet = conn.getMetaData().getCatalogs();

        while (resultSet.next()) {

          String databaseName = resultSet.getString(1);
            if(databaseName.equals(dbName)){
                return true;
            }
        }
        resultSet.close();

    }
    catch(Exception e){
        e.printStackTrace();
    }

    return false;
}

推荐答案

您可以使用 ,这里是获取目录(又名数据库名称)的示例

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();

这篇关于如何使用java检查mysql中的特定数据库是否已经存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 00:10