java.sql 크기를 얻으려면 어떻게 해야 하나요?결과 세트?
건건꽤 꽤단 ??? ???? 쪽도 없는 것 같아요.size()
않다length()
★★★★★★ 。
해요.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
입입 of ResultSet.TYPE_FORWARD_ONLY
이 상태를 유지하고 싶다(또한 이 상태로 전환하지 않는다).ResultSet.TYPE_SCROLL_INSENSITIVE
★★★★★★★★★★★★★★★★★」ResultSet.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);
[속도 고려]
의 로트는 「」을 나타내고 있습니다.ResultSet.last()
는 '을 '접속'으로 합니다.ResultSet.TYPE_SCROLL_INSENSITIVE
Derby의 임베디드형 데이터베이스 중 어느 것이 Derby에 비해 최대 10배 느리습니까?ResultSet.TYPE_FORWARD_ONLY
.
및 Derby를 H2로 호출하는 .SELECT COUNT(*)
를 클릭합니다.
ResultSet 사이즈를 취득하는 방법, ArrayList 사용 불필요 등
int size =0;
if (rs != null)
{
rs.beforeFirst();
rs.last();
size = rs.getRow();
}
사이즈가 표시됩니다.또, 결과 세트를 인쇄하기 전에, 다음의 코드 라인을 사용해 주세요.
rs.beforeFirst();
이것은 행 수를 세는 간단한 방법입니다.
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
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);
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 인터페이스의 런타임 값을 확인해보니 항상 ResultSetImpl과 거의 일치합니다.ResultSetImpl에는 다음과 같은 메서드가 있습니다.getUpdateCount()
원하는 값을 반환합니다.
이 코드 샘플로 충분합니다.
ResultSet resultSet = executeQuery(sqlQuery);
double rowCount = ((ResultSetImpl)resultSet).getUpdateCount()
다운캐스팅은 일반적으로 안전하지 않은 절차라는 것을 알지만 이 방법은 아직 실패하지 않았습니다.
오늘은 왜 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.
을 사용하다「」를 사용합니다.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
'IT이야기' 카테고리의 다른 글
Vue.js의 커스텀 디렉티브에서 클릭 이벤트를 캡처하려면 어떻게 해야 합니까? (0) | 2022.05.30 |
---|---|
vue 구성 요소가 이벤트를 전달하지 않습니다. (0) | 2022.05.30 |
nuxtvuetify는 SasError: ID가 필요합니다. (0) | 2022.05.30 |
구성 요소 내부에 생성된 FullCalendar 개체 내부에서 Vue 구성 요소 개체에 액세스하는 중 (0) | 2022.05.30 |
Vue 메서드 호출 (0) | 2022.05.29 |