select few rows from resultset mysql java - java

i have used a select command in my java program and stored its value in the result set. now while looping in the resultset i want to use a select command which will select the first 5 lines of the resultset and insert into other table. for the second time, it should select the next 5 lines and insert into the table. and for the third time, so on..
Statement s = connection.createStatement();
s.executeQuery("Select * from table1");
ResultSet res = s.getResultSet();
while(res.next()){
// here i want to select the first 5 lines of the result set and insert in the second table
}

Statement s = connection.createStatement();
s.executeQuery("Select * from table1");
ResultSet res = s.getResultSet();
while(res.next()){
// here i want to select the first 5 lines of the result set and insert in the second table
while(res.next() && (res.getRow()%5) !=0){
//select from this table
//call insert method(what selected)
}
}

I would suggest changing your query using LIMIT and using a PreparedStatement. Something like:
SELECT * FROM table1 LIMIT ?,?
This has a couple of advantages:
You are not fetching everything in one shot - can be sometimes a performance benefit if you've a lot many rows to deal with in your table
You can change pre-define the number of elements that you want to fetch in every single batch
So your code will look something like this:
PreparedStatement ps = null;
ResultSet rs = null;
final int FETCH_LIMIT = 5; //number of elements to fetch per batch
final int BATCH_LIMIT = 3; //number of batches you would want
int currentRows = 0;
try{
ps = connection.prepareStatement("SELECT * FROM table1 LIMIT ?,?");
for(int currentBatch = 0; currentBatch < BATCH_LIMIT; currentBatch++){
ps.clearParameters();
ps.setInt(1, currentRows);
ps.setInt(2, currentRows + FETCH_LIMIT);
try{
rs = ps.executeQuery();
while(rs.next()){
// do your work
}
}catch(Exception exe){
//manage exception
}finally{
//manage resultset
}
currentRows += FETCH_LIMIT;
}
}catch(Exception exe){
//Handle your exception
}
finally{
//Manage your resources
}

Please add a falg and use that is it
int i=0;
while(res.next() && i< 5){
//select from this table
//call insert method(what selected)
i++;
}

Create another insert query dynamically inside the while loop and execute it outside the while loop

Related

I don't get into a loop even though the ResultSet is full

I have a result set which is not empty. It contains 6 columns. But if I want to use the loop, nothing happens.
If I call the stored procedure in SQL Server Management Studio with the same parameters as in the Java code, I got a result:
A few minutes ago everything worked
// That doesn't work because I can't get into the loop
if (con != null) {
String an_id = "bkoubik";
String AS_Aufruf = "exec BfV_Web.sp_Anwender_Start\n#AnwenderID = ?";
try {
PreparedStatement STMT = con.prepareStatement(AS_Aufruf);
STMT.setString(1, an_id);
ResultSet rs = STMT.executeQuery();
//THIS IF STATEMENT IS NOT ENTERING, SO WHY THEN THE WHILE LOOP
IS NOT WORKING ?
if (!rs.next() ) {
System.out.println("no data");
}
ResultSetMetaData meta = rs.getMetaData();
int intRS = meta.getColumnCount();
//THE LOOP IS NOT ENTERING
while (rs.next()) {
[...]
}
intRS is the column count, not the row count. Your rs is likely empty.
The first call to rs.next() (before the loop) already consumes the one and only row, so the next call (in the while) will return false.

get size of ResultSet by using SELECT COUNT(*)

I want to retrieve all the data from database, and at the same time, I want to know how many rows of data I get. And this is my SQL:
rs = s.executeQuery("SELECT COUNT(*), * FROM tblUser");
Is this a valid SQL statement? and after I retrieved all the data, how to set them into different variables? For example, I have a column called UserIDin the database, I can simply get it by using rs.getString('UserID'), but how to get the result of the COUNT(*)?
Your SQL is not valid. The ANSI standard way to do what you want uses window functions:
select count(*) over () as total_cnt,
u.*
from tblUser u;
This adds a new column to every row -- which seems to be what you want. There are other mechanisms, depending on the underlying database for doing this.
The results you request are not interrelated, so run two queries:
rs1 = s.executeQuery("SELECT COUNT(*) FROM tblUser");
rs2 = s.executeQuery("SELECT * FROM tblUser");
and retrieve the values (one only for rs1) the usual way.
You can do this to count the rows in resultset
String query = "Select * from tblUser";
rs = s.executeQuery(query);
public int getCount(ResultSet rs) {
int rows = 0;
while(rs.next()) {
i++;
}
return i;
}
This way you can get the resultset as well as count
Since you are already accessing the recordset within VBA probably the simplest was to return the count of the record set is to:
rs = s.executeQuery("SELECT * FROM tblUser");
If Not rs.EOF Then
' Important: You must move to the last record to
' obtain the count of the full recordset
rs.MoveLast
rsCount = rs.RecordCount
' Remember to Return to the First Record so that you can
' continue to use the recordset
rs.MoveFirst
End If
An alternative if your RDBMS doesn't support window functions
rs = s.executeQuery("SELECT B.cnt, U.*
FROM tblUser U,
(SELECT count(*) cnt FROM tblUser) B");

JDBC show rows count

I want to print my rows count at the end, But it shows 1
public void showRecords() {
try {
Statement st1 = con.createStatement();
ResultSet result1 = st1.executeQuery("select * from mytable");
while (result1.next()) {
System.out.println(result1.getString(1) + " " + result1.getString(2));
}
ResultSet rs1 = st1.executeQuery("select count(*) from mytable");
int rows = rs1.last() ? rs1.getRow() : 0;
System.out.println("Number of rows is: "+ rows); //print 1
} catch (SQLException sqle) {
System.out.println("Can not excute sql statement");
sqle.printStackTrace();
}
}
Output:
...
Number of rows is: 1
Output: ... Number of rows is: 1
That's absolutely correct because the ouput of a count query like
select count(*) from mytable
would only contain a single row containing the total number of rows. For you to now retrieve that count you should make use of the Resultset's getter methods as usual.
int rows = rs1.getInt(1);
To retrieve the count the way you wanted to; use the same approach with your first query
ResultSet result1 = st1.executeQuery("select * from mytable");
int rows = result1.last() ? result1.getRow() : 0;
System.out.println("Number of rows is: "+ rows); // should print the count
The count(*) does not have a column name (or only a "generated" one that you might not know). Therefor you need to get the value by column index.
Additionally you need to call next() on the ResultSet in order to be able to obtain the value:
ResultSet rs1 = st1.executeQuery("select count(*) from mytable");
int rows = 0;
if (rs1.next() {
rows = rs1.getInt(1);
}
System.out.println("Number of rows is: "+ rows); //print 1
Selecting the count from a RecoredSet always returns a value of 1, i.e. the record containing the result of the query. You want
ResultSet rs1 = st1.executeQuery("select count(*) from mytable");
if (rs1.next()) {
int rows = rs1.getInt("COUNT")
}
You must read the value from the rowcount query, as it is a normal query. Like
rows = rs1.getInt(1);
I've written a blog post about retrieving query metadata without extra roundtrip, which is something people typically do to paginate their data. I really recommend you don't re-run your queries all the time just to count stuff. A simple approach would be to use window functions, which are now supported in a lot of SQL dialects:
SELECT *, count(*) OVER () FROM mytable
Of course, since you're using low level JDBC API to iterate your ResultSet, why not just count things in the client at that point? E.g.
try (ResultSet rs = s.executeQuery("select * from mytable")) {
int i = 0;
while (rs.next()) {
System.out.println(rs.getString(1) + " " + rs.getString(2));
i++;
}
System.out.println("Number of rows is: " + i);
}

Working with a ResultSet

I am trying to get a count from a particular table in my derby database, but when I run the code I keep getting Invalid operation at current cursor position
public int getNumUsers(){
ResultSet rs = null;
int size = -1;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("select count(*) from USERS");
while(rs.next()){
size = rs.getInt("COUNT");
}
stmt.close();
} catch (SQLException sqe) {
sqe.printStackTrace();
}
return size;
}
Change your query to
select count(*) As COUNT from USERS
or change your function call to
rs.getInt(1);
give an alias to count(*) in your select statement. in mysql we use as to give alias name.I dunno about derby though, but think it'd be similar.
rs = stmt.executeQuery("select count(*) as count from USERS");
while(rs.next()){
size = rs.getInt("count");
}

Java query find only the first entry

If I try the following query in Java, Java returns without any error only the first entry of the table. But if I copy the same query to Access, Access returns all 33 entries.
Query:
SELECT Country, Sum(SumOfNumber) AS number FROM CountryList WHERE Year=2012 AND (Month=1 Or Month=2 Or Month=3) AND Entity='xxx' GROUP BY Country ORDER BY Sum(SumOfNumber) DESC
rs.last();
System.out.println(rs.getRow());
returns 1.
Any advice?
Okay guys, now I deleted therm "ORDER BY Sum(SumOfNumber) DESC" and Java returned all Countries and throwed an exception at the end "invalid cursor status"
public void doconnect(){
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
conn = DriverManager.getConnection(ConnectURL,user,pw);
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
String query = "SELECT Country, Sum(SumOfNumbers) AS number FROM CountryList WHERE Year=2012 AND (Month=1 Or Month=2 Or Month=3) AND Entity='xxx' GROUP BY Country ORDER BY Sum(SumOfNumbers) DESC";
System.out.println(query);
ResultSet rs = stmt.executeQuery(query);
while(rs.next()){
System.out.println(rs.getString("Country"));
}
rs.close();
}
catch(Exception e){
System.err.println(e);
e.printStackTrace();
}
finally{
if(conn!=null){
try{
conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
Change
rs.last();
System.out.println(rs.getRow());
to (to get all countries)
while (rs.next()) {
System.out.println(rs.getString("Country"));
}
to get results from all rows instead of just the last one.
Of course you get only one row (the last one). This is because you go directly to the last row of the ResultSet using rs.last(). Try to iterate over the ResultSet in order to get all rows returned.
To see how many rows are returned you can run query : SELECT count(*) as count FROM CountryList WHERE Year=2012 AND (Month=1 Or Month=2 Or Month=3) AND Entity='xxx' and then get the count using
while(rs.next()){
int count = rs.getInt("count");
}
rs.last() moves the cursor to the last row in the resultSet which means that after you've read the line, no more data is available, i also suggest that you use the function provided by
Keppil: while (rs.next()) {
System.out.println(rs.getRow()); }
From java API resultSet.last()
Moves the cursor to the last row in this ResultSet object.
Check it here,
remove rs.last and iterating over resultset like this
while(rs.next()) {
sysout(rs.getString("your column name"));
}

Categories

Resources