本文介绍了Java中的ExecuteQuery()与getResultSet()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

statement.executeQuerystatement.getResultSet()有什么区别.我相信两者都会为选择语句返回ResultSet,但是当我们应该使用其中的哪个条件时有什么具体标准.

What is the difference between statement.executeQuery and statement.getResultSet(). I believe both will return ResultSet for a select statement but are there any specific criteria when we should use which of them.

推荐答案

通常,如果知道执行的是select语句,则应使用executeQuery. getResultSet()方法本身不执行该语句.

In general you should use executeQuery if you know you are executing a select statement. The getResultSet() method by itself does not execute the statement.

getResultSet旨在与execute结合使用. execute方法适用于未知的语句类型,或者可以产生多个结果(即0个或多个更新计数或结果集)的语句.

The getResultSet is intended to be used in combination with execute. The execute methods are intended for use with unknown statement types, or statements that can produce multiple results (that is 0 or more update counts or result sets).

简而言之:您通常应使用executeQuery.

So in short: you should normally use executeQuery.

一个简单的示例,如果代码不知道它将执行什么查询(更新,查询或更复杂的东西),例如在执行用户提供的查询时,应使用execute.

A simple example when you should use execute if the code doesn't know what query it is going to execute (an update, a query, or something more complex), for example when executing user provided queries.

另一个示例是SQL Server存储过程,该过程可以返回多个更新计数和结果集.

Another example are SQL Server stored procedures, which can return multiple update counts and result sets.

处理execute结果的通用方法是:

A generic way of processing a result of execute is:

boolean isResultSet = statement.execute(sql);
while (true) {
    if (isResultSet) {
        try (ResultSet rs = statement.getResultSet()) {
            // do something with result set
        }
    } else {
        int updateCount = statement.getUpdateCount();
        if (updateCount == -1) {
            // -1 signals no more results
            break;
        }
        // do something with update count
    }
    // move to next result
    isResultSet = statement.getMoreResults();
}

这确保所有结果都得到处理.

This ensures that all results get processed.

这篇关于Java中的ExecuteQuery()与getResultSet()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 12:17