建立连接后如何检查数据库是否存在 JAVA

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13743993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 13:51:09  来源:igfitidea点击:

How to check if a DataBase exist or not after the connection is made JAVA

javadatabaseexistsdatabase-engine

提问by SanRyu

I have a big question... I have a database java program creation.

我有一个大问题...我有一个数据库 java 程序创建。

I want to know if the database exists or not, and the if exists just connect, if not to create it.

我想知道数据库是否存在,如果存在只是连接,如果不创建它。

I tried this one:

我试过这个:

if (dbName.exists() == false) {}

THIS IS ALL THE CODE...

这就是全部代码...

Class.forName("com.mysql.jdbc.Driver");
System.out.println("MySQL JDBC driver loaded ok.");

THIS IS A BACKUP CODE FOR IT, JUST TO WORK FOR NOW.... PARTIAL CODE THAT WORKS !

这是它的备份代码,只是为了现在工作......部分代码有效!

conn = DriverManager.getConnection(DBurl + url
+ "?createDatabaseIfNotExist=true& + "
+ "useUnicode=true&characterEncoding=utf-8&user="
+ userName + "&&password=" + password);


System.out.println("Connected to database ");           
System.out.println("Connected to the database " + url);

BUT I WANT SOMETHING LIKE:

但我想要这样的东西:

FILE dbName = new FILE (url);
Statement stmt = new Statement;

if (dbName.exists() == true)
   System.out.println("Database exists ! Connecting ... ");
else {
   String sql = "CREATE DATABASE "+url;
   stmt.executeUpdate (sql);
}

I don't want to put the url with the password and username in the same place... because they are provided from an external part, but that is allready implemented and working.

我不想将带有密码和用户名的 url 放在同一个地方......因为它们是从外部提供的,但这已经实现并有效。

So I want to rip in 2 peaces, 1 Connect "jdbc:mysql://localhost:3306/"; WITHOUT URL which is the database NAME ... AND THEN IF A DATABASE DOES NOT EXISTS THERE WITH THAT NAME JUST CREATE ON.

所以我想在 2 和平,1 Connect "jdbc:mysql://localhost:3306/"; 没有 URL 是数据库名称......然后如果一个数据库不存在,那么就创建那个名称。

It is not working.... not entering in the elsemore, and says that Exeption Database already exists.

它不起作用......没有进入else更多,并说Exeption Database已经存在。

Thanks you very much.

非常感谢你。

回答by Udo Klimaschewski

If it is a MySQL database, the following code should work. Other databases may give a different error code, but the general way should be clear. Important is that you connect to the instance, not a specific database initially. For creating the tables, you will need to connect to the newly created database. You can't use the instance connection that I use in my example for creating the tables:

如果是 MySQL 数据库,下面的代码应该可以工作。其他数据库可能会给出不同的错误代码,但大致的方式应该是清楚的。重要的是您最初连接到实例,而不是特定的数据库。要创建表,您需要连接到新创建的数据库。您不能使用我在示例中使用的实例连接来创建表:

    Connection connection = null;
    Statement statement = null;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        connection = DriverManager.getConnection("jdbc:mysql://localhost/",
                "root", "admin");
        statement = connection.createStatement();
        String sql = "CREATE DATABASE DBNAME";
        //To delete database: sql = "DROP DATABASE DBNAME";
        statement.executeUpdate(sql);
        System.out.println("Database created!");
    } catch (SQLException sqlException) {
        if (sqlException.getErrorCode() == 1007) {
            // Database already exists error
            System.out.println(sqlException.getMessage());
        } else {
            // Some other problems, e.g. Server down, no permission, etc
            sqlException.printStackTrace();
        }
    } catch (ClassNotFoundException e) {
        // No driver class found!
    }
    // close statement & connection

回答by Michael J. Lee

Without knowing much about what's going on here simply trying to connect to a database that doesn't exists should throw a TimeoutExceptionerror or something similar. Just catch the exception and do stuff if you cannot connect.

在不太了解这里发生的事情的情况下,仅仅尝试连接到不存在的数据库应该会引发TimeoutException错误或类似的事情。如果您无法连接,只需捕获异常并执行操作即可。

boolean canConnect = false;
Connection conn = null;
try{
    conn = DriverManager.getConnection(...);
    canConnect = true;
}(Exception ex){
   canConnect = false;
}

if (!canConnect){
  makeDatabase(...);
}

Enjoy your day!

祝您愉快!

回答by joash

try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/", "root", "admin");
        Statement statement = connection.createStatement();
        String sql = "CREATE DATABASE IF NOT EXISTS DBNAME";
        statement.executeUpdate(sql);
    } catch (ClassNotFoundException | SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Kindly Note a Two things

请注意两件事

  1. The new driver class is `com.mysql.cj.jdbc.Driver'
  2. The query CREATE DATABASE IF NOT EXISTS DBNAMEmeans you dont have to check if database exits
  1. 新的驱动程序类是`com.mysql.cj.jdbc.Driver'
  2. 查询CREATE DATABASE IF NOT EXISTS DBNAME意味着您不必检查数据库是否存在