Programing

java.sql.ResultSet의 크기는 어떻게 얻습니까?

lottogame 2020. 3. 27. 07:57
반응형

java.sql.ResultSet의 크기는 어떻게 얻습니까?


이것은 매우 간단한 작업이 아니어야합니까? 그러나 나는 방법 size()도 없습니다 length().


DO가 SELECT COUNT(*) FROM ...대신 쿼리를.

또는

int size =0;
if (rs != null) 
{
  rs.last();    // moves cursor to the last row
  size = rs.getRow(); // get row id 
}

두 경우 모두 전체 데이터를 반복 할 필요가 없습니다.


ResultSet rs = ps.executeQuery();
int rowcount = 0;
if (rs.last()) {
  rowcount = rs.getRow();
  rs.beforeFirst(); // not rs.first() because the rs.next() below will move on, missing the first element
}
while (rs.next()) {
  // do your standard per row stuff
}

글쎄, 당신이 ResultSet타입 을 가지고 있다면 ResultSet.TYPE_FORWARD_ONLY그것을 그렇게 유지하고 싶 거나 ( 을 사용하기 위해 또는 로 전환 하지 않기를 원한다 ).ResultSet.TYPE_SCROLL_INSENSITIVEResultSet.TYPE_SCROLL_INSENSITIVE.last()

행 수를 포함하는 첫 번째 가짜 / 포니 행을 맨 위에 추가하는 매우 훌륭하고 효율적인 해킹을 제안합니다.

쿼리가 다음과 같다고 가정 해 봅시다.

select MYBOOL,MYINT,MYCHAR,MYSMALLINT,MYVARCHAR
from MYTABLE
where ...blahblah...

출력은 다음과 같습니다

true    65537 "Hey" -32768 "The quick brown fox"
false  123456 "Sup"    300 "The lazy dog"
false -123123 "Yo"       0 "Go ahead and jump"
false       3 "EVH"    456 "Might as well jump"
...
[1000 total rows]

코드를 다음과 같이 리팩터링하면됩니다.

Statement s=myConnection.createStatement(ResultSet.TYPE_FORWARD_ONLY,
                                         ResultSet.CONCUR_READ_ONLY);
String from_where="FROM myTable WHERE ...blahblah... ";
//h4x
ResultSet rs=s.executeQuery("select count(*)as RECORDCOUNT,"
                           +       "cast(null as boolean)as MYBOOL,"
                           +       "cast(null as int)as MYINT,"
                           +       "cast(null as char(1))as MYCHAR,"
                           +       "cast(null as smallint)as MYSMALLINT,"
                           +       "cast(null as varchar(1))as MYVARCHAR "
                           +from_where
                           +"UNION ALL "//the "ALL" part prevents internal re-sorting to prevent duplicates (and we do not want that)
                           +"select cast(null as int)as RECORDCOUNT,"
                           +       "MYBOOL,MYINT,MYCHAR,MYSMALLINT,MYVARCHAR "
                           +from_where);

쿼리 출력은 이제 다음과 같습니다.

1000 null     null null    null null
null true    65537 "Hey" -32768 "The quick brown fox"
null false  123456 "Sup"    300 "The lazy dog"
null false -123123 "Yo"       0 "Go ahead and jump"
null false       3 "EVH"    456 "Might as well jump"
...
[1001 total rows]

그래서 당신은 단지

if(rs.next())
    System.out.println("Recordcount: "+rs.getInt("RECORDCOUNT"));//hack: first record contains the record count
while(rs.next())
    //do your stuff

int i = 0;
while(rs.next()) {
    i++;
}

사용할 때 예외가 발생했습니다 rs.last()

if(rs.last()){
    rowCount = rs.getRow(); 
    rs.beforeFirst();
}

:

java.sql.SQLException: Invalid operation for forward only resultset

기본적으로는이므로 ResultSet.TYPE_FORWARD_ONLY사용할 수 있습니다.rs.next()

해결책은 다음과 같습니다.

stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_READ_ONLY); 

[속도 고려]

여기에 많은 ppl이 제안 ResultSet.last()하지만 ResultSet.TYPE_SCROLL_INSENSITIVEDerby 내장 데이터베이스의 경우보다 최대 10 배 느린 연결을 열어야합니다 ResultSet.TYPE_FORWARD_ONLY.

임베디드 Derby 및 H2 데이터베이스에 대한 나의 마이크로 테스트에 따르면 SELECT COUNT(*)SELECT 전에 호출하는 것이 훨씬 빠릅니다 .

여기 내 코드와 벤치 마크에 대한 자세한 내용이 있습니다.


행 수를 수행하는 간단한 방법입니다.

ResultSet rs = job.getSearchedResult(stmt);
int rsCount = 0;

//but notice that you'll only get correct ResultSet size after end of the while loop
while(rs.next())
{
    //do your other per row stuff 
    rsCount = rsCount + 1;
}//end while

ResultSet의 크기를 얻는 방법, ArrayList 등을 사용할 필요가 없음

int size =0;  
if (rs != null)   
{  
rs.beforeFirst();  
 rs.last();  
size = rs.getRow();
}

이제 크기가 생깁니다. 결과 집합을 인쇄하려면 다음 코드 줄을 사용하여 인쇄하십시오.

rs.beforeFirst();  

ResultSet 인터페이스 의 런타임 값을 확인하고 거의 항상 ResultSetImpl 이라는 것을 알았습니다 . ResultSetImpl에는 getUpdateCount()찾고자하는 값을 리턴 하는 메소드 가 있습니다.

이 코드 샘플은 다음과 같이 충분합니다.
ResultSet resultSet = executeQuery(sqlQuery);
double rowCount = ((ResultSetImpl)resultSet).getUpdateCount()

다운 캐스팅은 일반적으로 안전하지 않은 절차이지만이 방법으로 아직 실패하지는 않았습니다.


        String sql = "select count(*) from message";
        ps =  cn.prepareStatement(sql);

        rs = ps.executeQuery();
        int rowCount = 0;
        while(rs.next()) {
            rowCount = Integer.parseInt(rs.getString("count(*)"));
            System.out.println(Integer.parseInt(rs.getString("count(*)")));
        }
        System.out.println("Count : " + rowCount);

     }

오늘 나는이 논리를 사용하여 RS의 수를 모르는 이유를 알았습니다.

int chkSize = 0;
if (rs.next()) {
    do {  ..... blah blah
        enter code here for each rs.
        chkSize++;
    } while (rs.next());
} else {
    enter code here for rs size = 0 
}
// good luck to u.

theStatement=theConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

ResultSet theResult=theStatement.executeQuery(query); 

//Get the size of the data returned
theResult.last();     
int size = theResult.getRow() * theResult.getMetaData().getColumnCount();       
theResult.beforeFirst();

나는 같은 문제를 겪고 있었다. ResultSet.first()실행 직후에 이런 식으로 사용하면 다음 과 같이됩니다.

if(rs.first()){
    // Do your job
} else {
    // No rows take some actions
}

문서 ( 링크 ) :

boolean first()
    throws SQLException

커서를이 ResultSet객체 의 첫 번째 행으로 이동 합니다.

보고:

true커서가 유효한 행에있는 경우 false결과 집합에 행이없는 경우

던졌습니다 :

SQLException-데이터베이스 액세스 오류가 발생한 경우 이 메소드는 닫힌 결과 세트에서 호출되거나 결과 세트 유형이TYPE_FORWARD_ONLY

SQLFeatureNotSupportedException -JDBC 드라이버가이 메소드를 지원하지 않는 경우

이후:

1.2


가장 쉬운 방법 인 Run Count (*) 쿼리는 resultSet.next ()를 수행하여 첫 번째 행을 가리킨 다음 resultSet.getString (1)을 수행하여 개수를 가져옵니다. 코드 :

ResultSet rs = statement.executeQuery("Select Count(*) from your_db");
if(rs.next()) {
   int count = rs.getString(1).toInt()
}

열 이름을 지정하십시오 ..

String query = "SELECT COUNT(*) as count FROM

ResultSet 객체의 열을 int로 참조하고 거기에서 논리를 수행하십시오.

PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, item.getProductId());
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
    int count = resultSet.getInt("count");
    if (count >= 1) {
        System.out.println("Product ID already exists.");
    } else {
        System.out.println("New Product ID.");
    }
}

참고 URL : https://stackoverflow.com/questions/192078/how-do-i-get-the-size-of-a-java-sql-resultset

반응형