I am passing the following query to a ResultSet object:
String query = "SELECT COUNT( DISTINCT KEY ), SOURCE FROM MY_TBL\n" +
"GROUP BY SOURCE\n" +
"ORDER BY SOURCE";
I want to capture the counts I am getting for each SOURCE and sum them into a total. How can I capture these counts via ResultSet since COUNT isn't a column name in the ResultSet and I don't think I can return it's value via rs.getInt("COUNT")?
getInt is overloaded, use index (an int) instead of a column name:
rs.getInt(1); // the first column is 1
Try having alias
String query = "SELECT COUNT( DISTINCT KEY ) AS COUNT, SOURCE FROM MY_TBL\n" +
"GROUP BY SOURCE\n" +
"ORDER BY SOURCE";
I Think it is better to use
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * from Customer");
ResultSetMetaData rsmd = rs.getMetaData();
int numCols = rsmd.getColumnCount();
I think "getColumnCount" retinto number of column in a table instead of number of rows...
Related
I have a scenario here I need to compare 2 database tables using java
First Database table has
id Name Salary
1 ABC 1000
2 XYZ 2000
3 LMN 3000
Second Database Table has
id Name Salary
4 PQR 5000
2 XYZ 2000
1 ABC 4000
3 LMN 2500
I had used list to compare but is there any other way to compare 1st table with the 2nd table using selenium java.
I want the output to be
Second table has 4 rows while 1 table has 3 rows (or vice versa)
1st table LMN salary is 3000 and second table LMN salary is 2500
I would do the requested comparison in SQL directly. This will be faster. There are a couple of ways to do this depending on the results you need.
Since you are using Microsoft SQL you can retrieve the number of rows in the requested format by doing something like this:
SELECT 'The FirstTable has ' + cast((SELECT count(*) from FirstTable) as varchar(50)) + ' records, while the SecondTable has ' + cast((SELECT count(*) from SecondTable) as varchar(50)) + ' records';
For getting the differences between the tables you can do something like this:
SELECT * FROM FirstTable
UNION
SELECT * FROM SecondTable
EXCEPT
SELECT * FROM FirstTable
INTERSECT
SELECT * FROM SecondTable;
Then you can take ResultSet and compare the entries like this:
while (resultSet.next())
{
int id= rs.getInt("id");
String name= rs.getString("name");
int firstTableSalary = rs.getInt("salary");
rs.next();
int secondTableSalary = rs.getInt("salary");
console.log(String.format("The first table salary is %d, while the second table salary is %d, name=%s, id=%d", firstTableSalary, secondTableSalary, name, id);
}
I prepared here a fiddle for checking the SQLs.
Getting the salary differences is easier with SQL
String query = "select t1.name,t1.salary t1_salary, t2.salary t2_salary" +
" from table1 t1, table2 t2 "+
" where t1.id=t2.id and t1.name=t2.name and t1.salary!=t2.salary";
//this will give you a result set of all the names and salaries from the two tables
//where the salaries differ.
Connection conn = ...
try (Statement stmt = conn.createStatement()){
ResultSet rs = stmt.executeQuery(query);
while (rs.next()){
String name = rs.getString(1);
Integer t1Salary = rs.getInt(2);
Integer t2Salary = rs.getInt(3);
//do something with these values
}
rs.close();
Similarly, capture the table lengths with queries
int t1Length = 0;
int t2Length = 0;
rs = stmt.executeQuery("select count(*) from table1");
while (rs.next()){
t1Length = rs.getInt(1);
}
rs.close();
rs = stmt.executeQuery("select count(*) from table2");
while (rs.next()){
t2Length = rs.getInt(1);
}
rs.close();
//do something with the lengths
}
conn.close();
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");
I have a first resultset within which I have to iterate through userids and for each userid, I have to perform several select count(*)'s all of which return single valued outputs. If you haven't understood what I said, please follow the pseudo code below:
ResultSet rs = stmt.executeQuery("select userid from tablename");
while(rs.next()){
String userid = rs.getString("userId");
ResultSet rs1 = stmt.executeQuery("select count(*) as cnt1 from xxx.... where userId = "+userId);
if(rs1.next())
String count1 = rs1.getString("cnt1");
rs1.close();
ResultSet rs2 = stmt.executeQuery("select count(*) as cnt2...");
if(rs2.next())
String count2 = rs2.getString("cnt2");
rs2.close();
....
rs10.close();
Since this is inefficient, I was hoping to get past Resultset each time by writing some sort of direct query to retrieve each different count like
String cnt1 = stmt.executeQuery("select count(*) as noE from useractiontable where curr_action='edit'" + " and userId = " + userId).getString("noE");
I know something like this cannot be done without using rs.next() each time. Is prepare statement the way to go? Is there another way? Appreciate any pointers in this regard.
You can use group by to retrieve all the user with count(*)
ResultSet rs = stmt.executeQuery("select userid,count(*) from tablename group by userid");
I suspect that you can do all the DB work in one query and then just have one result set to read. It would be much more efficient and much cleaner code. I am thinking something like:
select userid, count(*) as cnt
from tablename t inner join othertablename ot on t.userid = ot.userid
group by userid
If you have other columns in tablename that you want, you would add them to the select and to the group-by. For example:
select userid, username, count(*) as cnt
from tablename t inner join othertablename ot on t.userid = ot.userid
group by userid, username
The above queries will not return userid's with a count of zero. If you want the ones with zeros, use an outer join (and make the counting logic deal with the null case):
select userid, username, isnull(count(ot.userid), 0) as cnt
from tablename t left outer join othertablename ot on t.userid = ot.userid
group by userid, username
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);
}
I am trying to get the mysql command like mysql_insert_id(); which retrieve the last inserted row's auto_increment id. What can I do to get it in Java?
rs = st.executeQuery("select last_insert_id() from schedule");
lastid = rs.getString("last_insert_id()");
my lastid was declared as INT. I dono what to use in rs.get and also the parameter..
Using JDBC, you can use Connection.PreparedStatement(query, int) method.
PreparedStatement pstmt = conn.prepareStatement(Query, Statement.RETURN_GENERATED_KEYS);
pstmt.executeUpdate();
ResultSet keys = pstmt.getGeneratedKeys();
keys.next();
key = keys.getInt(1);
Try using an alias
rs = st.executeQuery("select last_insert_id() as last_id from schedule");
lastid = rs.getString("last_id");
see this post for answer & explanation
Statement stmt = db.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
numero = stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()){
risultato=rs.getInt(1);
}
Why not
SELECT MAX(id) FROM schedule
If id your column has a different name than id, you need to replace it accordingly in the above query.
You can use it like:
rs = st.executeQuery("SELECT MAX(id) AS id FROM schedule");
int lastid = rs.getInt("id");
You can use following query to get last auto_incremented ID of last inserted row.
SELECT (max(auto_incr_id)) from table_name;
Another option:
SELECT id FROM table_name ORDER BY id DESC LIMIT 1;
another way:
ResultSet rs = stmt.executeQuery("SELECT last_insert_id()");
while(rs.next()){
System.out.println("id = " + rs.getLong(1));
}