Get the number of the affected rows - java

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.

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);

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

How to run SQL(MYSQL) stored procedure in JAVA jdbc?

I'm a MySQL user and I have been using following statements in MySQL Workbench :
(these statements are based on Select column names whose entries are not null)
SET group_concat_max_len = 4294967295;
SELECT GROUP_CONCAT(
' SELECT ',QUOTE(COLUMN_NAME),
' FROM ( select * from table_name where s3_01 = ', coloumn1,' ) abc',
' WHERE `',REPLACE(COLUMN_NAME, '`', '``'),'` IS NOT NULL',
' HAVING COUNT(*)'
SEPARATOR ' UNION ALL ')
INTO #sql
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'table_name';
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Although it work in my workbench, I do not know how to make it work in java.
for example, I made following code:
String sql1 = "SET group_concat_max_len = 4294967295;";
String sql2 = " SELECT GROUP_CONCAT(' SELECT ',QUOTE(COLUMN_NAME), ' FROM ( select * from ptc_weight where s3_01 = ',column1,' ) abc', ' WHERE `',REPLACE(COLUMN_NAME, '`', '``'),'` IS NOT NULL', ' HAVING COUNT(*)' SEPARATOR ' UNION ALL ') INTO #sql FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'ptc_weight'; ";
String sql3 = " PREPARE stmt FROM #sql; ";
String sql4 = " EXECUTE stmt;";
String sql5 = " DEALLOCATE PREPARE stmt;";
String[] result = getResult(sql1+sql2+sql3+sql4+sql5);
public static String[][] getResult(String sql) {
System.out.println(sql);
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
String[][] resultTable = null;
try {
con = getCon();
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
ResultSetMetaData result = rs.getMetaData();
int rowNum=0;
// Go to the last row
rs.last();
rowNum = rs.getRow();
// Reset row before iterating to get data
rs.beforeFirst();
int colNum = result.getColumnCount();
resultTable = new String[rowNum][colNum];
for(int itr1=0; itr1<rowNum; itr1++){
rs.next();
for(int itr2=0; itr2<colNum; itr2++){
resultTable[itr1][itr2] = rs.getObject(itr2+1).toString();
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
dbclose(con, ps, rs);
}// finally
return resultTable;
}
However, it does not work. I guess I made a wrong code for utilizing stored procedure, but I don't have any idea to deal with this problem.
CallableStatement callableStatement = null;
String getDBUSERByUserIdSql = "{call getDBUSERByUserId(?,?,?,?)}";
callableStatement.setInt(1, 10);
callableStatement.registerOutParameter(2, java.sql.Types.VARCHAR);
callableStatement.registerOutParameter(3, java.sql.Types.VARCHAR);
callableStatement.registerOutParameter(4, java.sql.Types.DATE);
// execute getDBUSERByUserId store procedure
callableStatement.executeUpdate();
String userName = callableStatement.getString(2);
String createdBy = callableStatement.getString(3);
Date createdDate = callableStatement.getDate(4);
System.out.println("UserName : " + userName);
System.out.println("CreatedBy : " + createdBy);
System.out.println("CreatedDate : " + createdDate);
Here Is Full Example. You can modify your code as you need.
Simple one with less argument and with resultset :
CallableStatement cstmt = con.prepareCall("{call getEmployeeDetails(?, ?)}");
cstmt.setInt("employeeId", 123);
cstmt.setInt("companyId", 456);
ResultSet rs = cstmt.executeQuery();

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).

Get Array From List Of Rows?

I was curious on how to get a list of rows and add values from each row to an array in Java.
Here is what it looks like in PHP:
<?php
$result = mysql_query("SELECT * FROM names");
while($row = mysql_fetch_array($result)) {
// Get variables from this row and such
}
?>
I can't seem to find out how to do this in Java.
Resolution Found
Statement sta = con.createStatement();
ResultSet res = sta.executeQuery("SELECT TOP 10 * FROM SalesLT.Customer");
while (res.next()) {
String firstName = res.getString("FirstName");
String lastName = res.getString("LastName");
System.out.println(" " + firstName + " " + lastName);
}
If you want to use pure JDBC you can follow the example from the JDBC tutorial:
public void connectToAndQueryDatabase(String username, String password) {
Connection con = DriverManager.getConnection(
"jdbc:myDriver:myDatabase", username, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next()) {
int x = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
}
}
But most people don't do this any more; you can, for example, use an ORM like hibernate to abstract the database a bit.

Categories

Resources