Getting row count with Result Set - java

Please Help !!!!!!!
In DB I have 2 rows with this query.
SELECT D.DEALER_CODE
FROM SCOTT.T_DEALERSHIP D,SCOTT.T_DEALER_BILLING DB
WHERE D.DEALER_CODE = DB.DEALER_CODE
AND DEALER_NAME LIKE 'XTIME%'
AND (RNR_CUST_NUM = '546' OR RNR_CUST_NUM = '43356'OR RNR_CUST_NUM = '7637055' OR RNR_CUST_NUM ='7637055' OR RNR_CUST_NUM IS NULL)
AND (RCI_STORE_NUMBER IS NULL OR RCI_STORE_NUMBER = '05')
AND (RCI_AREA_NUMBER = '01'OR RCI_AREA_NUMBER IS NULL)
AND (RCI_DEALER_NUMBER IS NULL AND DEALER_Address1 LIKE UPPER('1500 ORACLE%')
AND DEALER_CITY =UPPER('BAKERSFIELD') AND DEALER_ZIP LIKE'6%')
With below code, I get only 1 row when there are 2 records in DB. When there is only one record in DB it works but not when there are more records. Also rs.last() method gets skipped and exits resultset. I have to comment it to execute for one record. I do not want to use COUNT.
ResultSet rs = stmt.executeQuery(sql1);
System.out.println("" + sql1);
while(rs.next()) {
rs.last();
int Rows = rs.getRow();
System.out.println("Rows are " + Rows);
}

If all you want to do is count the records in the database, then you should really use a query of the form SELECT count(*) FROM .... If you really need to perform the query the way you listed above, then you want to set a counter variable outside your while loop like so:
int rowNum = 0;
while (rs.next()) {
rowNum++;
}
System.out.println("Number of records: "+rowNum);

I strongly recommend against returning all the data to Java via JDBC just to determine the number of rows. If you just want to know how many rows match the condition, then do a select count(*) query:
In SQL:
SELECT COUNT(*)
FROM SCOTT.T_DEALERSHIP D,SCOTT.T_DEALER_BILLING DB
WHERE D.DEALER_CODE = DB.DEALER_CODE
AND DEALER_NAME LIKE 'XTIME%'
AND (RNR_CUST_NUM = '546' OR RNR_CUST_NUM = '43356'OR RNR_CUST_NUM = '7637055' OR RNR_CUST_NUM ='7637055' OR RNR_CUST_NUM IS NULL)
AND (RCI_STORE_NUMBER IS NULL OR RCI_STORE_NUMBER = '05')
AND (RCI_AREA_NUMBER = '01'OR RCI_AREA_NUMBER IS NULL)
AND (RCI_DEALER_NUMBER IS NULL AND DEALER_Address1 LIKE UPPER('1500 ORACLE%')
AND DEALER_CITY =UPPER('BAKERSFIELD') AND DEALER_ZIP LIKE'6%')
Then in Java:
ResultSet rs = stmt.executeQuery(sql1);
System.out.println("" + sql1);
int rows = 0;
if(rs.next()) {
rows = rs.getInt();
}
System.out.println("Rows are " + rows);
Edit based on OP's comments
To get the values from the database in addition to the count, just scan the values.
SQL:
SELECT D.DEALER_CODE
FROM SCOTT.T_DEALERSHIP D,SCOTT.T_DEALER_BILLING DB
WHERE D.DEALER_CODE = DB.DEALER_CODE
AND DEALER_NAME LIKE 'XTIME%'
AND (RNR_CUST_NUM = '546' OR RNR_CUST_NUM = '43356'OR RNR_CUST_NUM = '7637055' OR RNR_CUST_NUM ='7637055' OR RNR_CUST_NUM IS NULL)
AND (RCI_STORE_NUMBER IS NULL OR RCI_STORE_NUMBER = '05')
AND (RCI_AREA_NUMBER = '01'OR RCI_AREA_NUMBER IS NULL)
AND (RCI_DEALER_NUMBER IS NULL AND DEALER_Address1 LIKE UPPER('1500 ORACLE%')
AND DEALER_CITY =UPPER('BAKERSFIELD') AND DEALER_ZIP LIKE'6%')
Java:
ResultSet rs = stmt.executeQuery(sql1);
System.out.println("" + sql1);
List<String> rows = new ArrayList<String>();
while(rs.next()) {
rows.add(rs.getString());
}
System.out.println("There are " + rows.size() + " rows.");

Related

Varying content of an SQL update statement in java

I need to write an update function where its content is different based on what parameters are passed, e.g. if I have updateBook(int id, String title, String author, int pages), I have to do something like:
String sql;
if((!title.equals("null"))&&(!author.equals("null"))&&(pages>0)))
sql = "UPDATE book SET title='"+title+"', author='"+author+"', pages="+pages;
else if(((!title.equals("null"))&&(!author.equals("null")))
sql = "UPDATE book SET title='"+title+"', author='"+author+"'";
else if(((!title.equals("null"))&&(pages>0)))
sql = "UPDATE book SET title='"+title+"', pages="+pages;
... //and so on
sql = sql + " WHERE bookid="+id+";";
The more fields I have in my table, the more checks I have to do, which is uncomfortable, and requires me to write a lot of code.
Also, doing something like:
sql = "UPDATE book SET ";
if(!title.equals("null"))
sql = sql +"title='"+title+"',";
if(!author.equals("null"))
sql = sql+"author='"+author+"',";
if(pages>0)
sql = sql+"pages="+pages";
sql = sql + ";";
can't work since the unwanted commas cause statement errors.
You can see as well that if I have something like 6, 7, 8 etc field the checks start to get too many, and I can't also do more separated update statements as if something goes wrong I would need to rollback any query that has been done in that function.
Is there any way round to get a custom update statement having to write few code?
Firstly, use a PreparedStatement.
I would do it something like the following.
List<Object> params = new ArrayList<>();
StringBuilder sql = new StringBuilder();
if(!title.equals("null")) {
sql.append("title = ?");
params.add(title);
}
if(!author.equals("null")) {
if (sql.length() > 0) {
sql.append(", ");
}
sql.append("author = ?");
params.add(author);
}
if(pages>0) {
if (sql.length() > 0) {
sql.append(", ");
}
sql.append("pages = ?");
params.add(pages);
}
if (sql.length() > 0) {
sql.insert(0, "UPDATE book SET ");
sql.append(" WHERE bookid=?");
java.sql.Connection conn = // however you obtain it
java.sql.PreparedStatement ps = conn.prepareStatement(sql.toString());
for (int i = 0; i < params.size(); i++) {
ps.setObject(i + 1, params.get(i));
}
ps.executeUpdate();
}

How do I retrieve a single cell from MySQL database using query and assigned it to a variable in Java Netbeans Apache

First I am going to try using query to retrieve the int min_stock single cell using the item description. Then put that value into a variable. I want to be able to have the variable minStock to be equal to a number. I want to use it to make operations in my program.
PreparedStatement cm = con.prepareStatement(checkMinimumStock);
ResultSet minS = cm.executeQuery("SELECT min_stock FROM items WHERE item_description = '"+item+"'");
int minStock = minS.getInt("min_stock");```
you are choose wrong way to use PrepareStatment.
you have two option to do :
1:
String sql = "SELECT min_stock FROM items WHERE item_description = ?";
PreparedStatement cm = con.prepareStatement(sql);
cm.setString(1, item);
ResultSet rs = cm.executeQuery();
2:
String sql = "SELECT min_stock FROM items WHERE item_description = '" + item + "'";
ResultSet rs = con.createStatement().executeQuery(sql);
and then
if (rs.next())
int minStock = rs.getInt("min_stock");
else
//not found any match row in DB table
Try this
String checkMinimumStock = "SELECT min_stock FROM items WHERE item_description = ? ";
PreparedStatement cm = con.prepareStatement(checkMinimumStock);
cm.setString(1,item);
ResultSet minS = cm.executeQuery();
if(minS.next()){
int minStock = rs.getInt("min_stock");
}
String checkMinimumStock = "SELECT min_stock FROM items WHERE item_description = ? ";
Forgot to add this in the beginning of the code!

Display nth row from table DB in Java using getString?

I want to show data from a Table Database using SQLite in JAVA
my code:
String sql = "SELECT * FROM DIC";
rs = st.executeQuery(sql);
System.out.println("row 1: " + rs.getString("WORD")); // WORD is a column label
System.out.println("row 3: " + rs.getString("WORD"))
With DIC is my table
so How do I can show value in nth row ( ex: 2nd, 3th,.. row)???
Specifically, I want my code print out as desired. Thank you!
String sql = "SELECT * FROM DIC";
rs = st.executeQuery(sql);
int rowCount = 0;
while(rs.next){
rowCount++
if(rowCount == ?) {
System.out.println("row 1: " + rs.getString("WORD"));
System.out.println("row 3: " + rs.getString("WORD"))
}
}
You could use OFFSET in you query and use prepared statement
SELECT mycol FROM DIC ORDER BY mycol LIMIT 1 OFFSET ?;
And you need to bind it as
stmt.setInt(1,nth_row);

Building a dynamic SQL query based on user input in Java

If I have a search module which has the following:
search box, dropdown 1, dropdown 2.
And I have a query like this:
SELECT * FROM MY_TABLE where q1 = 'searchBox' AND q2 = 'dropdown1' AND q3 = 'dropdown2'
How can I make that query dynamic depending on user filter, so if the user only fills the search box, the query will be:
SELECT * FROM MY_TABLE where q1 = 'searchBox'
If the user fills search box and dropdown1, the query will be:
SELECT * FROM MY_TABLE where q1 = 'searchBox' AND q2 = 'dropdown1'
and if the user doesn't fill anything, the query will be:
SELECT * FROM MY_TABLE
I am using Java.
There are frameworks that can help with this:
QueryDSL
jOOQ
Squiggle
Hibernate
If you'd like to create a quick and simple solution, you can do something like the following:
List<String> params = new ArrayList<>();
StringBuilder sb = new StringBuilder();
sb.append("SELECT * FROM MY_TABLE WHERE 1 = 1");
if (searchBox != null) {
sb.append(" AND q1 = ?");
params.add(searchBox);
}
if (dropdown1 != null) {
sb.append(" AND q2 = ?");
params.add(dropdown1);
}
if (dropdown2 != null) {
sb.append(" AND q3 = ?");
params.add(dropdown2);
}
PreparedStatement preparedStatement = connection.prepareStatement(sb.toString());
for (int i = 1; i <= params.size(); i++) {
preparedStatement.setString(i, params.get(i));
}
ResultSet resultSet = preparedStatement.executeQuery();
To improve upon the code provided by #blacktide
PreparedStatement preparedStatement = connection.prepareStatement(sb.toString());
for (int i = 1; i <= params.size(); i++) {
preparedStatement.setString(i, params.get(i));
}
You would instead want the line within the for loop to be
preparedStatement.setString(i, params.get(i-1));
Since arrays start at 0, we'd want to grab that zeroth index to set the first value added to the list to the first value to be updated in the SQL string. Otherwise you would grab the second value within params which would not be the intended value.

Cannot update multiple times using for loop

I have a form that borrows stocks from branchA to branchB. The user can input multiple products and I do this by having a text area split it with (","), and place in it an array. After submitting my form, I insert it in a table and then update the stocks from another table. Here is my code (which I actually placed in a JSP file instead of a normal Java class):
try {
for (int iCtr=0; iCtr<idsplit.length; iCtr++) {
sInsertQuery = "INSERT INTO PULLOUT_REPORTS (control_number, dateofpullout, item_des, item_size, item_qty, pullout_from, pullout_to) values ('"+cn+"','"+po+"','"+idsplit[iCtr]+"','"+issplit[iCtr]+"','"+qtsplit[iCtr]+"','"+fr+"','"+to+"')";
pInsertPullout = conn.prepareStatement(sInsertQuery);
pInsertPullout.executeUpdate();
if (fr.equals("Antipolo") && to.equals("Binangonan")) {
sUpdateRecord = "UPDATE maintable SET antip_qty = antip_qty - ? WHERE item_code = ? AND item_size = ?";
pUpdateFrom = conn.prepareStatement(sUpdateRecord);
pUpdateFrom.setString(1,qtsplit[iCtr]);
pUpdateFrom.setString(2,idsplit[iCtr]);
pUpdateFrom.setString(3,issplit[iCtr]);
pUpdateFrom.addBatch();
pUpdateFrom.executeBatch();
sUpdateRecord1 = "UPDATE maintable SET binang_qty = binang_qty + ? WHERE item_code = ? AND item_size = ?";
pUpdateTo = conn.prepareStatement(sUpdateRecord1);
pUpdateTo.setString(1,qtsplit[iCtr]);
pUpdateTo.setString(2,idsplit[iCtr]);
pUpdateTo.setString(3,issplit[iCtr]);
pUpdateTo.addBatch();
pUpdateTo.executeBatch();
} }
}
catch (Exception e) {
response.sendRedirect("error.jsp");
}
The first query successfully inserts multiple rows in the table but my second query only updates the first index from the array. I don't know what I could be doing wrong since they're both inside the same loop.
Any help please?
UPDATE: I did this .addBatch and .executeBatch and it work a while, now it doesn't work again. It only updates the first index.
Try something like this snippet (i might ve messed up with types of your variables, because I guessed them.
try {
sInsertQuery = "INSERT INTO PULLOUT_REPORTS " +
"(control_number, dateofpullout, item_des, item_size, item_qty, pullout_from, pullout_to)" +
" values " +
"(?,?,?,?,?,?,?)";
pInsertPullout = conn.prepareStatement(sInsertQuery);
sUpdateRecord = "UPDATE maintable SET antip_qty = antip_qty - ? WHERE item_code = ? AND item_size = ?";
pUpdateFrom = conn.prepareStatement(sUpdateRecord);
sUpdateRecord1 = "UPDATE maintable SET binang_qty = binang_qty + ? WHERE item_code = ? AND item_size = ?";
pUpdateTo = conn.prepareStatement(sUpdateRecord1);
for (int iCtr=0; iCtr<idsplit.length; iCtr++) {
pInsertPullout.setLong(1, cn);
pInsertPullout.setLong(2, po);
pInsertPullout.setString(3, idsplit[iCtr]);
pInsertPullout.setString(4, issplit[iCtr]);
pInsertPullout.setString(5, qtsplit[iCtr]);
pInsertPullout.setString(6, fr);
pInsertPullout.setString(7, to);
pInsertPullout.executeUpdate();
pInsertPullout.clearParameters();
if (fr.equals("Antipolo") && to.equals("Binangonan")) {
pUpdateFrom.setString(1,qtsplit[iCtr]);
pUpdateFrom.setString(2,idsplit[iCtr]);
pUpdateFrom.setString(3,issplit[iCtr]);
pUpdateFrom.addBatch();
pUpdateTo.setString(1,qtsplit[iCtr]);
pUpdateTo.setString(2,idsplit[iCtr]);
pUpdateTo.setString(3,issplit[iCtr]);
pUpdateTo.addBatch();
}
}
pUpdateFrom.executeBatch();
pUpdateTo.executeBatch();
}
catch (Exception e) {
response.sendRedirect("error.jsp");
}
and don't forget to cleanup resources afterwards. Close statements and connection in finally{} clause.

Categories