我正在 Java 11 中使用 intelliJ 和 MYSQL 制作一个 FXML 应用程序,它允许用户创建一个具有自己选择名称的数据库。应用:
- 发现数据库尚不存在
- 通过使用不带特定数据库名称的 URL 的连接字符串创建数据库
- 连接到新数据库并执行 sql.txt 文件,从而创建所有必需的表。
这种方法有效,除了以下事实之外:当执行下面代码的最终语句时,会弹出一个自动警报:
“无法连接到数据库。请关闭程序,检查驱动程序是否可用以及连接详细信息是否正确,然后再次尝试登录”。
即使已创建并连接了包含所有必需表的新数据库,它也会执行此操作。
问题:是否有办法禁用此自动生成的消息?
protected void execute() throws Exception {
// Connect using URL without DBNAME:This is a re-assignment of inherited value
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Create database at user request:
String sql = "CREATE DATABASE " + this.newDBName;
stmt = conn.prepareStatement(sql);
stmt.executeUpdate(sql);
StringBuilder sqlText = new StringBuilder();
File file = new File(this.getClass().getResource("createSQLScript.txt").toURI());
/*
Read in the Sql statement text file resource to create tables
using try-with resources and automatic resource closure.*/
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
sqlText.append(line);
}
}
// Set connection object to allow multiple queries in createSQLScript.txt
// A re-assignment of inherited value
conn = DriverManager.getConnection(DB_URL + this.newDBName + "?allowMultiQueries=true", USER, PASS);
stmt = conn.prepareStatement(sqlText.toString());
stmt.executeUpdate(sqlText.toString());
}
PS:DB_URL是 - jdbc:mysql://localhost:3306/
最佳答案
这可能与您在一个连接中创建数据库并开始在另一个连接中访问它而不关闭前一个连接这一事实有关。
Connection
和 PreparedStatement
是可关闭的资源。您应该始终使用 try-finally
或 try-with-resources
模式关闭它们,例如:
try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS)) {
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
// execute stmt...
// populate database...
}
}
try (Connection conn = DriverManager.getConnection(
DB_URL + this.newDBName + "?allowMultiQueries=true", USER, PASS) {
// access newly created database...
}
关于java - Java连接新的MYSQL数据库时阻塞 "Unknown database"消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55005500/