使用executeUpdate进行SELECT查询的行为

时间:2012-12-19 06:53:38

标签: java oracle jdbc

我错误地使用Statement#executeUpdate()执行SELECT查询时遇到了一种奇怪的行为。虽然Javadoc明确指出executeUpdate() throws SQLException,如果给定的SQL语句生成ResultSet对象。但是当我执行SELECT * from TABLE_NAME时,我没有任何异常。相反,我得到的返回值与no相同。选择的行数,如果没有。小于等于10.如果不是。超过10,返回值总是10。

Connection conn;
Statement stmt;
try {
    conn = getConnection();
    stmt = conn.createStatement();
    int count = stmt.executeUpdate("SELECT * from TABLE_NAME");
    log.info("row count: " + count);
} catch (SQLException e) {
    log.error(e);
    // handle exception
} finally {
    DbUtils.closeQuietly(stmt);
    DbUtils.closeQuietly(conn);
}

我正在使用 Oracle 10g

我在这里遗漏了什么,还是由司机来定义自己的行为?

6 个答案:

答案 0 :(得分:4)

这种行为与Statement.executeUpdate API相矛盾。有趣的是什么, java.sql.Driver.jdbcCompliant API说"如果驱动程序通过了JDBC兼容性测试,那么它只能在此处报告为#34;。我测试了oracle.jdbc.OracleDriver.jdbcCompliant - 它返回true。我还测试了com.mysql.jdbc.Driver.jdbcCompliant - 它返回false。但是在你所描述的相同情况下抛出

Exception in thread "main" java.sql.SQLException: Can not issue SELECT via executeUpdate().

似乎JDBC驱动程序无法预测。

答案 1 :(得分:3)

根据规范Statement.executeUpdate()方法返回the row count for SQL Data Manipulation Language (DML)

UPD :我尝试对返回的结果做出假设(总是< = 10)。看来,oracle语句的实现在这里返回了这样称为premature batch count的数量(根据反汇编的源代码Or​​aclePreparedStatement类)。这以某种方式与更新语句相关联。默认情况下,此值可能等于10

UPD-2:根据:Performance ExtensionsThe premature batch flush count is summed to the return value of the next executeUpdate() or sendBatch() method.

答案 2 :(得分:2)

您正在使用的查询不会生成ResultSet但显然会影响行。这就是为什么你没有得到一个SQLException,而是一个受影响的行数的计数。谜团是为什么它不超过10.可能是Oracle JDBC驱动程序实现特定。

答案 3 :(得分:1)

您的SQL查询是从table_name检索所有行。因此,您可以使用execute()方法而不是executeUpdate()方法。因为后面的方法一般使用当你的任务是相关的数据库操作语言,如更新查询。

答案 4 :(得分:1)

使用

int count = stmt.executeQuery(“SELECT * from TABLE_NAME”);

而不是

int count = stmt.executeUpdate(“SELECT * from TABLE_NAME”);

获得总数。行

答案 5 :(得分:0)

对于一般情况(选择或更新):

    Statement st = conn.createStatement();
    st.execute(sql);