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

时间:2015-02-14 04:48:20

标签: java mysql sql database jdbc

假设我在MySQL中实现一个查询

Create Database newdb;

然后数据库响应结果

database created in 0.05 sec

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

2 个答案:

答案 0 :(得分:3)

以下代码适用于我

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.

答案 1 :(得分:1)

不,你不能那样做。至少不是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的返回值为0时,它可能意味着以下两种情况之一:

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

  • 执行的语句是DDL语句。

Documentation