我正在用Java 11中的intelliJ和MYSQL制作一个FXML应用程序,该应用程序允许用户创建一个具有自己选择名称的数据库。应用程序:
这种方法行之有效,因为以下代码的最终语句执行自动警报时会弹出以下信息:
“无法连接到数据库。请关闭程序,检查驱动程序是否可用并且连接详细信息正确,然后尝试重新登录。”
即使已创建并连接了具有所有必需表的新数据库,它仍会执行此操作。
问题:反正有什么功能可以禁用此自动生成的消息?
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 /
答案 0 :(得分:0)
这可能与您在一个连接中创建数据库并在不关闭前一个连接的情况下开始在另一个连接中访问数据库有关。
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...
}