How to get only 5 rows with JDBC from ResultSet? - java

I have a select SQL that may get many rows of data.
And I only want the first 5 rows.
Besides adding rownums = 5 or adding statement.setMaxRows(5).
Can I get the result from using java coding?
Thanks.
I tried for loop and while(rs.next() && i < 5). all of them does not work.
try (Connection connection = abc.getConnection();
PreparedStatement statement = connection.prepareStatement(sql))
{
statement.setString(1,idNum);
ResultSet rs = statement.executeQuery();
for (int i = 0; i < 5; i++) {
while (rs.next()) {
itemList.add(rs.getString("idName"));
}
}
}
It shows all of the result in the itemList from the select SQL.

Currently, a single iteration of your loop exhausts the whole resultset.
You may want to add up end conditions like :
for (int i = 0; i < 5 && rs.next(); i++) {
itemList.add(rs.getString("idName"));
}
Note that your attempt with while(rs.next() && i < 5) should also work, you were probably just missing the increment of i .

You can read only the first 5 rows from the resultSet on the client side, but ideally you should be limiting number of rows returned by the database. Use limit 5 in the query.
This will avoid a lot of unnecessary work needed to return those extra rows from the database to client.

Your query is responsible to fetch data from DB , so better to control retrieve rows from db itself, this will avoid your java code checks. use limit 5 in your query based on your requirements.

Related

How to get last insert in Java Derby

I am trying to get the last ID inserted on the Java Derby DataBase.
This is a little program that i did, but i think that could be better ways to do that:
Query queryUsuarios = em.createNamedQuery("Usuario.findAll");
List<Usuario> listUsuario = queryUsuarios.getResultList();
int i=0;
for (i = 0; i < listUsuario.size(); i++) {
Usuario verUsuario = em.find(Usuario.class, i);
if(verUsuario != null) {
System.out.println(i+")"+verUsuario.getNombres());
}
}System.out.println("The last ID is "+i);
The main question is, there is a better and more secure way to do this?. Because i think on this way i could get errors in the future...
Thank you!.
You can do it using LIMIT and order by.Check below:
SELECT * FROM `table_name` ORDER BY `table_id` desc LIMIT 1;

Java statement.setFetchSize() works well when ResultSet size == Fetch size

I have a problem with retrieving data from Oracle database. I use ojdbc8 and my code is:
Statement stmt = conn.createStatement();
stmt.setFetchSize(20000);
ResultSet rs = stmt.execute(sql);
while(rs.next()) {
for(int i = 0; i < columnCounter; i++) {
logger.info(rs.getString(i) + " ");
}
}
What I don't understand here is that when my query returns let say 53000 rows all together then in while loop first 40000 rows are printed in console very quickly but then there is a huge 20-25 seconds break, nothing happens and after that the rest rows are printed. It is always like that. If my query returns 81000 rows then 80000 rows is printed very quickly then long brake and then missing 1000 rows.
So I don't know why but it looks like when in ResultSet I have exactly 20000 rows which is a fetch size then it goes well, but if the ResultSet has less than number set in FetchSize then it slow downs. Can anyone explain what is going on here and how to fix it to get rid of this huge gap/brake??

how to mark a row as dead or used after using it in the java program

i have a table called user_request
req_id user_id name num_of_seats startplace
1 11 arjun 3 Mumbai
2 12 chethan 2 delhi
3 13 raj 4 pune
I have a java program that uses above details to schedule the seats which selects the first user_id on the table, so that the first request is performed,
stmt1 = conn.createStatement();
{
ResultSet rs1 = stmt
.executeQuery("SELECT num_of_seats FROM user_request ORDER BY req_id ASC LIMIT 1");
while (rs1.next()) {
size = rs1.getInt("num_of_seats");
System.out.println("the number of seats requested:-" + size);
}
//
code to perform scheduling using the details retrieved
//
now after this in the next run of the program I want the program to select the second row, so that the query should select the items from the second row and then the third, how can I do that??? I'm not getting a proper idea.. please help me...
the proper way to do it is to get everything out and then loop it within the java program.
The way you are doing it will put a lot more stress on the server/DB which under 99% of the case is MUCH slower than running some checking in the program itself.
try this
(sorry don't have an easy way to check my code, so it MIGHT have syntax error, but a least you'll get the idea)
stmt1 = conn.createStatement();
ResultSet rs1 = stmt.executeQuery("SELECT num_of_seats FROM user_request ORDER BY req_id");
int[] size = null;
if (rs1.next()) {
size = (int[])rs1.getArray("num_of_seats").getArray();
}
for(int i=0;i<size.length;i++){
System.out.println("the number of seats requested:-" +size[i]);
}

Fetching single row result without iterating in loop from Mysql using Java

I have a simple query that returns only count of rows.
select count(*) cnt from table
I can read it by iterating through resultset.
like
while(rs.next()){
int rowCount= rs.getInt(cnt);
}
But is there any way,using which I can get count directly without looping.
How about:
int rowCount = rs.next() ? rs.getInt(cnt) : -1;
It doesn't save you much though

Access String Array outside of two loops

I have an array of Strings created inside of a while loop nested inside a for loop. This has to do with creating an array from a column of strings in Derby but I will leave out some stuff for simplicity's sake.
The reason I am not providing the full code is because the problem is very specific. I am having no problems whatsoever with my database, resultset, statements, or queries. It's just accessing the array outside of the two loops.
//in the class,
private int rowCount; //Count of the rows in my column of strings
public String stringArray[];
//in the method I am using
public void myMethod() {
rowCount = 4; //In my code it actually counts it, lets say its four though.
stringArray = new stringArray[rowCount]; //set
for (int i = 0; i < rowCount; i++) {
while (rs.next()/*rs is simply a result set of a statement executeQuery to select the correct table*/)
{
stringArray[i] = rs.getString(2); //2 is the column number in the table
}
}
//Need to access stringArray here. When I try to print out values, it always prints out as null.
}
Thanks!
There's something wrong with your nested loops. For each row (each value of i / each execution of the outer loop), you iterate through your whole result set and overwrite stringArray[i] (i not chaning) many times.
When you get to the second row (i.e. i is 1 or higher), rs.next() will already be false, since you tranversed the whole rs in the first iteration of the outer loop.
Maybe you just need to replace your inner loop while(rs.next()) with a single call to rs.next()
Perhaps in your actual code, where you say:
rowCount = 4; //In my code it actually counts it, lets say its four though.
you are performing the count of the rows by doing something like:
for( rowCount = 0; rs.next(); rowCount++ ) { }
If you're doing something like that, then you've basically read all the rows already during the counting phase, and when you try to re-process the rows later the rs.next() method simply returns false since it's already read all the rows.
Of course, I'm just guessing...

Categories