使用 JDBC 获取 MySQL 查询的状态消息(包括执行时间)

Get status message of MySQL query (including execution time) with JDBC

假设我在 MySQL 中实现一个查询,比如说

Create Database newdb;

然后数据库响应结果

database created in 0.05 sec

现在我的问题是如何使用 JDBC 在 Java 程序中获取此消息?

不,你不能那样做。至少 JDBC 不是。你所能做的就是 -

Class.forName(jdbcDriver);
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/?user=root&password=");
Statement statement = connection .createStatement();
int result = statement.executeUpdate("CREATE DATABASE IF NOT EXISTS" + dbName)

你会得到 result 作为 0。

请注意,当 executeUpdate 的 return 值为 0 时,它可能表示以下两种情况之一:

  • 执行的语句是影响零行的更新语句。

  • 执行的语句是DDL语句。

Documentation

下面的代码适合我

try (Statement s = conn.createStatement()) {
    s.execute("SET PROFILING=1;");
    s.execute("CREATE DATABASE newdb;");
    try (ResultSet rs = s.executeQuery("SHOW PROFILES;")) {
        rs.next();
        System.out.printf(
                "     Statement: %s%nExecution time: %f seconds.%n", 
                rs.getString("Query"), 
                rs.getDouble("Duration"));
    }
    s.execute("SET PROFILING=0;");
}

控制台输出为

     Statement: CREATE DATABASE newdb
Execution time: 0.002014 seconds.