How to get count from resultset? - java

ResultSet rs = statement.executeQuery("SELECT COUNT(DISTINCT `id`) FROM `users`");
in MySQL i have answer "5" , how to get this 5 from resultset in java? int.

Get it as an int column :
int count = -1;
if (rs.next()) {
count = rs.getInt(1);
}

Try aliasing the COUNT(DISTINCT ID), then retrieving the alias from the ResultSet. This will be more readable and easier to maintain if you end up adding more logic to the query later.
ResultSet rs = statement.executeQuery("SELECT COUNT(DISTINCT `id`) as NUM_ROWS FROM `users`");
int count = -1;
if(rs.next())
{
count = rs.getInt("NUM_ROWS");
}

Related

set value = 0 while updating record in jsp

im trying to update a column using jsp
here i want my count column value to be updated as zero
count = 0
how can i do that. through this code value is not updating
String code = request.getParameter("code");
Connection conn = null;
Statement st=null;
ResultSet rs = null;
PreparedStatement ps = null;
int count = 0;
try{
conn = DataBaseConnection.initializeDatabase();
String query1 = null;
conn.setAutoCommit(false);
query1 = "update employee set count = ? where code= ' +code+' ";
ps = conn.prepareStatement(query1);
ps.setInt(1, count);
ps.executeUpdate();
}
catch (Exception e) {
e.printStackTrace();
}
here is my record in db
employee table
CODE VARCHAR2(12)
COUNT NUMBER(3)
You can replace
"update employee set count = ? where code= ' +code+' ";
with
"update employee set count = ? where code= '" + code + "'";
e.g. if the value of code is xyz then after this change, the query will become:
"update employee set count = ? where code= 'xyz'";
However, I recommend you do it as follows to avoid the SQL Injection:
query1 = "update employee set count = ? where code= ?";
ps = conn.prepareStatement(query1);
ps.setInt(1, count);
ps.setString(2, code);

Get the number of the affected rows

I am trying to get the number of the affected records of this query SELECT mac, stop_name from behaviour where mac = ? with the use of the executeQuery. How can I get the number of the affected rows?
Code:
if (behaviourExist.next()) {
PreparedStatement prepared = con
.prepareStatement("SELECT mac, stop_name from behaviour where mac = ?");
prepared.setString(1, macD);
ResultSet rsBehav = prepared.executeQuery();
ArrayList<String> stopNameList = new ArrayList<String>();
while (rsBehav.next()) {
//int numberOfRows = rsBehav.getInt(1);
String stNa = rsBehav.getString("stop_name");
if (stNa.equals(nameShortestDistance)) {
stopNameList.add(stNa);
}
}
}
This is a read operation so it will not affect any row. If you want to get the number of row returned then you could do one of the below
Use a counter variable and increment it in the loop while (rsBehav.next())
Use a scrollable resultset
PreparedStatement prepared = con.prepareStatement(
"SELECT mac, stop_name from behaviour where mac = ?",
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rsBehav = prepared.executeQuery();
rsBehav.afterLast();
int numRow = rsBehav.getRow();
rsBehav.beforeFirst();
Here numRow will give you number or row returned,
PreparedStatement prepared = con
.prepareStatement(
"SELECT (SELECT count(*) from where mac = ?),"
" mac, stop_name from behaviour where mac = ?");
prepared.setString(1, macD);
prepared.setString(2, macD);
ResultSet rsBehav = prepared.executeQuery();
ArrayList<String> stopNameList = new ArrayList<String>();
while (rsBehav.next()) {
int numberOfRows = rsBehav.getInt(1);
String stNa = rsBehav.getString("stop_name");
// ....
if (behaviourExist.next()) {
PreparedStatement prepared = con
.prepareStatement("SELECT mac, stop_name from behaviour where mac = ?");
prepared.setString(1, macD);
ResultSet rsBehav = prepared.executeQuery();
ArrayList<String> stopNameList = new ArrayList<String>();
int numberOfRows = 0;
while (rsBehav.next()) {
++numberOfRows;
String stNa = rsBehav.getString("stop_name");
if (stNa.equals(nameShortestDistance)) {
stopNameList.add(stNa);
}
}
}
Here the variable numberOfRows will increment each time the loop runs which will give you the total number of rows in the resultSet.

Java JDBC: how to get int size of table, by exectuning SQL query

Part of my code looks like this:
int size = 0;
try {
String query = "SELECT count(*) FROM users";
statement = connection.prepareStatement(query);
statement.execute(query);
I don't know what to do to set size of table to my int size.
The result set will contain the value of numner of rows. get the value into your size variable.
ResultSet result = statement.executeQuery(query);
while (result.next()){
size= result.getInt(1);
}
System.out.println("Number of row:"+size);
int size = 0;
try {
String query = "SELECT count(*) FROM users";
statement = connection.prepareStatement(query);
ResultSet rs = statement.execute(query);
size = rs.getInt(1);
rs.getInt(1) will return the first row from the query as int

Getting ResultSet columns and values dynamiclly

I am running an SQL query on a AS400 table.
I dont know in advance the columns names i am extracting in my SQL.
in my ResultSet i need to:
get the result set columns (MetaData of the result records - one time).
for each record on the set get the values of the columns.
How can i do this?
There are DataBaseMetaData retrieved from Connection.getMetaData() and ResultSetMetaData from a ResultSet.
Some example java code snipped that may help you:
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery( "SELECT * FROM MY_TABLE" );
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
/*if you need the column names...*/
//for( int i = 1; i <= numberOfColumns ) {
// rsmd.getColumnName( i );
//}
List<Object[]> result = new ArrayList<Object[]>();
while( rs.next() ) {
Object[] values = new Object[ numberOfColumns ];
for( int index = 0; index < numberOfColumns; ) {
values[ index ] = rs.getObject( ++index );
}
result.add( values );
}

Correct way to find rowcount in Java JDBC

I have tried different ways to get the row count in java JDBC, nut none seemed to be giving the correct result. Is there anything wrong that I am doing ?
Even though the customer table is empty and I should be getting the rowcount as 0, I don't understand why I get a non zero rowcount value.
Method 1 -
query = "SELECT * FROM customer WHERE username ='"+username+"'";
rs = stmt.executeQuery(query);
ResultSetMetaData metaData = rs.getMetaData();
rowcount = metaData.getColumnCount();
Method 2 -
query = "SELECT * FROM customer WHERE username ='"+username+"'";
rs = stmt.executeQuery(query);
rowcount = rs.last() ? rs.getRow() : 0;
See this snippet of code:
import java.io.*;
import java.sql.*;
public class CountRows{
public static void main(String[] args) {
System.out.println("Count number of rows in a specific table!");
Connection con = null;
int count = 0;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctutorial","root","root");
try {
Statement st = con.createStatement();
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter table name:");
String table = bf.readLine();
ResultSet res = st.executeQuery("SELECT COUNT(*) FROM "+table);
while (res.next()){
count = res.getInt(1);
}
System.out.println("Number of row:"+count);
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
This the way I use to get the row count in Java:
String query = "SELECT * FROM yourtable";
Statement st = sql.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );
ResultSet rs = st.executeQuery(query);
int rows = 0;
rs.last();
rows = rs.getRow();
rs.beforeFirst();
System.out.println("Your query have " + rows + " rows.");
When you working with JDBC that does not support TYPE_FORWARD_ONLY use this method to get rowcount.
Statement s = cd.createStatement();
ResultSet r = s.executeQuery("SELECT COUNT(*) AS rowcount FROM TableName");
r.next();
int count = r.getInt("rowcount");
r.close();
System.out.println("MyTable has " + count + " row(s).");
You can Get Row count using above method.
Thanks..
In Android, having no results returns an error. So check this case before incrementing count in while(resultset.next())
if(resultset!=null)
{
//proceed with incrementing row count function
}
else
{
// No resultset found
}
Just iterate and count
ResultSet result = sta.executeQuery("SELECT * from A3");
int k=0;
while(result.next())
k++;
System.out.print(k); //k is the no of row
As method name specifies metaData.getColumnCount() will return total number of columns in result set but not total no of rows (count).

Categories

Resources