How to use a same resultset twice in Java - java

I would like to use same result set twice, once is to check whether it is empty and execute code based on the result, and then, using (resultset.next() the second result set will always skip a line because of the first result set
Here's my code so far :
connection = DriverManager.getConnection(connection);
statement = (Statement) connection.createStatement();
resultset = statement.executeQuery(query);
String id = "0";
String idfromdb;
if(resultset.next() == false){
System.out.println("table is empty")
statement.executeUpdate(" INSERT INTO table VALUES ('value') ");
}
else{
while(resultset.next()){
idfromdb = resultset.getString("value")
if(! idfromdb = id){
System.out.println("no similar data has been found");
}
else{
System.out.println("similar data has been found");
}
}
}

When you call resultset.next() it will fetch one record,so you need to call previous() to reset the cursor
The full code:
boolean hasRecord = true;
if(!resultset.next()){// you are missing ) here
System.out.println("table is empty")
statement.executeUpdate(" INSERT INTO table VALUES ('value') ");
hasRecord = false;
}
if(hasRecord){
resultset.previous();//move to the previous record
}

Change to do-while loop:
if(resultset.next() == false{
System.out.println("table is empty")
statement.executeUpdate(" INSERT INTO table VALUES ('value') ");
} else {
do {
idfromdb = resultset.getString("value")
if(! idfromdb = id){
System.out.println("no similar data has been found");
}
else{
System.out.println("similar data has been found");
}
} while(resultset.next());
}
do-while evaluates its expression at the bottom of the loop instead of the top.

Related

Select Specific value from multiple rows returned by Oracle database

I am trying to compare a specific value from the values returned by database.
I am getting multiple rows from STORESTAFF but I am trying to compare one of the values returned from the table..
contains() and
equals()
are not working.
String qry = "Select all employe_id from storestaff where post='Admin'";
pstmnt = conn.prepareStatement(qry);
ResultSet rs2 = pstmnt.executeQuery(qry);
if (rs2.next()) {
String aa = rs2.getString("employe_id");
if (aa.contains(UN.getText())) {
this.aa = aa;
JOptionPane.showMessageDialog(null, "Exists");
} else {
JOptionPane.showMessageDialog(null, "Username doesn't Exist");
}
}
Can anyone suggestt me a better solution for it or can tell me the better solution for it?
If you use if it will return the first values, in your case you have to use while, which loop throw all the results, so you can check multiple results, instead you can use :
boolean check = false;
while (rs2.next()) {
String aa = rs2.getString("employe_id");
if (aa.contains(UN.getText())) {
this.aa = aa;
check = true;//if the value exist change the variable to true
break; //and break the loop
}
}
//when you end you have to check the value, if true then the user exist else no
if (check) {
JOptionPane.showMessageDialog(null, "Exists");
} else {
JOptionPane.showMessageDialog(null, "Username doesn't Exist");
}
Change if(rs2.next()) to while(rs2.next()) You are getting bulk data, so you need to iterate over it to compare one of the value which you want

ResultSet.next() row counter fails to count

I'm trying to figure out why this won't count and show Rows: 2 when I enter "ashton" for username and "ashton" for password. In my database I inserted 2 entries of username and password.
Here's the screenshot of table:
Here's the GRAB file:
Here's my code:
private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {
String userNameEntered = userNameTxtField.getText().trim();
String passwordEntered = passwordTxtField.getText().trim();
if(userNameEntered.isEmpty() || passwordEntered.isEmpty()){
JOptionPane.showMessageDialog(this, "Please fill out all fields");
}
else{
String username = "jordan";
String password = "jordan";
String dbURL = "jdbc:derby://localhost:1527/JDBCSTUDY";
Connection myConnection = null;
ResultSet myRs = null;
String SQL = "SELECT * FROM USERS WHERE USERNAME = ? AND PASSWORD = ?";
try {
myConnection = DriverManager.getConnection(dbURL,username,password);
JOptionPane.showMessageDialog(null, "Successfully Connected To Database");
PreparedStatement myPrepStmt = myConnection.prepareStatement(SQL,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
myPrepStmt.setString(1,userNameEntered); //assigns a string value to the first ?
myPrepStmt.setString(2,passwordEntered); //assigns a string value to the second ?
myRs = myPrepStmt.executeQuery(); // executes the select query and stores it to myRs
if(myRs.next() == false){//next() method returns true if the select statement is satisfied or if query is valid
JOptionPane.showMessageDialog(this, "Not found");
}
int countRows = 0;
while(myRs.next()){
countRows++;
if((myRs.getString(2).equals(userNameEntered))
&& (myRs.getString(3).equals(passwordEntered))){
JOptionPane.showMessageDialog(this,"found" +"\nRows: " + countRows );
}
}
} //end of try
catch (SQLException e) {
//if an exception or an error even occured while executing the try{} block, the 3 lines will be printed
System.err.println("Error message: " + e.getMessage());
System.err.println("Error Code: " + e.getErrorCode());
System.err.println("SQL State: " + e.getSQLState());
}
finally{
if(myConnection!=null){
try {
myConnection.close();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null,"Error encountered: " + ex.toString());
}
}//end of if
}//end of finally
}
}
In my understanding, next() returns true if the SELECT query is successful or if there are rows when cursor is moved by next(). I need to be able to count the rows to show that there are more than 1 row holding the same username and password. I can't proceed on making another ifelse for counting duplication of username and password because in my code, it doesn't seem to count 2 rows.
I'd appreciate any help.
Thanks.
this is the output i get,
This is what I did, and it worked. Thanks for the suggestions guys! It's helping me learn more.
int countRows = 0;
while(myRs.next()){
countRows++;
}
if(countRows == 0)
{
JOptionPane.showMessageDialog(this, "User details doesn't exist. \n Please register first");
}
else if(countRows > 1) //if there are duplications
{
JOptionPane.showMessageDialog(null, "User details found but has more 1 one entry" +
"\nFound: " + countRows + " users" );
}
else if(countRows == 1){
JOptionPane.showMessageDialog(null, "User Found");
}
Your error is to call rs.next twice: Every time you call next you are implicitly discarding the last state of the cursor. It's a good (and clearer) practice to read the resultset's columns after every call to next.
In your case, it's enough to move if after the while loop, changing the condition:
int countRows = 0;
while(myRs.next()){
countRows++;
...
}
if (countRows==0)
{
JOptionPane.showMessageDialog(this, "Not found");
}
The main problem is you call myRs.next() two times before getting data.
You can use
myRs.isBeforeFirst()
as described here
or use this template as described here
if (!myRs.next() ) {
System.out.println("no data");
} else {
do {
//statement(s)
} while (myRs.next());
}
And you don't need loop at all — just use a SQL request with count
SELECT COUNT(*) FROM USERS WHERE USERNAME = ? AND PASSWORD = ?

proceed to next mySQL row JAVA

I ran into problem when my query returns result and I cannot check the next row.
//here i assume that only "regular" is correct room type
public boolean checkAvalibility(String roomType, String checkInDate, String checkOutDate ) throws SQLException{
database db = new database();
db.connect();
this.roomType = roomType;
if(roomType!="regular"){
System.out.println("please select correct room type");
return false;
}
myStmt = db.myConn.prepareStatement("select * from Rooms where "
+ "RoomType = ?");
myStmt.setString(1, roomType);
myRs = myStmt.executeQuery();
boolean val = myRs.next();
while(val){
if(roomType.equals(myRs.getString("RoomType"))){
System.out.println("correct room type");
isType = true;
}
if(isType == true){
int roomNumber = myRs.getInt("idRooms");
if(checkDateAvailability(checkInDate, checkOutDate, roomNumber)==true){
return true;
}
else{
return false;
}
}
}
System.out.println();
return false;
}
this code here
private boolean checkDateAvailability(String checkInDate,String checkOutDate, int roomNumber) throws SQLException{
database db = new database();
db.connect();
myStmt = db.myConn.prepareStatement("select idRooms, CheckIn, CheckOut from Rooms where "
+ "CheckIn=? AND RoomType=?");
myStmt.setString(1, checkInDate);
myStmt.setString(2, roomType);
myRs = myStmt.executeQuery();
boolean val = myRs.next();
while(val){
//calcDateBeetween simply takes check-in date which is in database and current check-out date converts them to integer value and compares the difference
if(calcDateBetween(checkOutDate, myRs.getString("CheckIn")) <=0 ){
System.out.println("You can book the room");
return true;
}
else{
System.out.println("Dates occupied");
return false;
}
}
if(val==false){
System.out.println("room is available for booking date is empty");
return true;
}
else{
System.out.println("i have no idea of what im doing");
}
return false;
}
As a pre-requirement, let's say I want to have only two rows and I don't need new records. If I send check-IN(!) date which matches the one in database (in Check-in column) then everything works fine, and I have print out saying that date is occupied. But if I send check-in value ex. 23-01-2015 and check-out 03-02-2015 it does not go to calcDateBetween() method, probably assuming that if query was empty then the table can be updated and I have a printout that dates are available for booking. What can be the solution in this situation and why it does not compare dates in second case?
Thanks !
There are a couple of issues here. Instead of
boolean val = myRs.next();
while(val){
write
while(myRs.next()) {
Otherwise, you're not checking each time whether there are more rows; you're just using the same true or false value each time.
Also, within your while loop, you have return true; and return false; - and one of these is going to run each time. That will make your method end, and your loop won't run again. You probably don't want these return statements in there.

Validation in delete query in java

I have a problem in validating my delete query anything I type even if the data is not on my database it keeps deleting it says success I want it to have an error if the user type a data that is not exists in the database. Here's my code:
try{
System.out.println("Enter record you want to delete: ");
frail = scn.nextLine();
}catch(Exception ee){
System.out.println(ee.getMessage());
}
try{
stmt = conn.createStatement();
String sqlII = "delete from tbl_test where test_name = ?";
PreparedStatement psII = conn.prepareStatement(sqlII);
psII.setString(1, frail);
psII.executeUpdate();
int rowAffacted = psII.executeUpdate();
if (rowAffacted != 0) {
System.out.println("Deleted!");
}else{
System.out.println("No Affected Rows!");
}
}
catch(Exception eer){
System.out.println(eer.getMessage());
}
psII.executeUpdate(); returns an int. If these value is zero, no lines are delete, so you can see that the user exists is not in the database and you can show an error. Is the user is corect, the value should be grater than zero.
int noOfAffectedRows =psII.executeUpdate();
if (noOfAffectedRows = 0){
//show Error
}
You could catch the return value of executeUpdate as below:
int rowAffacted = psII.executeUpdate();
if (rowAffacted != 0) {
System.out.println("Deleted!");
}
Javadoc for executeUpdate's return value says
either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing
executeUpdate() returns the number of rows altered or returns 0 in case no rows are affected, so in your case you can do something like:
int alteredRows=psII.executeUpdate();
if(alteredRows==0)
{
System.out.println("No rows deleted");
}
else
{
System.out.println(alteredRows +"rows deleted");
}

compare integer text field value with mysql data in java

I want to check whether the newly entered data is already in the table
code:
txtNo = new JTextField();
{
try {
Class.forName("com.mysql.jdbc.Driver");
String srcurl1 = "jdbc:mysql://localhost:3306/DB_name";
Connection con = DriverManager.getConnection(srcurl1,"root","paswrd");
Statement stmt1 = con.createStatement();
ResultSet rs1 = stmt1.executeQuery("select No from bank where No='"+txtNo.getText()+"' ");
int ch =rs1.getInt("No");
int ch4= Integer.parseInt(txtNo.getText());
if(ch==ch4) // input 58 == 58
System.out.println("already exits");
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
Error :
Exception:java.sql.SQLException: Illegal operation on empty result set.
You need to check if the result set has elements or not:
while(rs1.next())
{
int ch = rs1.getInt("No");
// ...
}
You get this exception when the select statement returns an empty set. Add a try/catch block which acts upon the knowledge that the data is not already in the table in the catch block.
You need to check the ResultSet first to check to see that it contains rows:
if (rs1.next()) {
int ch =rs1.getInt("No");
...
}
The easiest way to check whether a particular record exists in the database might be just as follows:
Select 1 from bank where No = [your_supplied_value]
This query would return 1 if it finds a row in your database with the supplied data or return an empty resultset. So, all you need to check is whether ANY value is returned in the resultset or whether it is emtpy.
Here's a sample code to get you started:
txtNo = new JTextField();
{
try {
String compareText = txtNo.getText().trim();
if(compareText.length() > 0){
Class.forName("com.mysql.jdbc.Driver");
String srcurl1 = "jdbc:mysql://localhost:3306/DB_name";
Connection con = DriverManager.getConnection(srcurl1,"root","paswrd");
Statement stmt1 = con.createStatement();
ResultSet rs1 = stmt1.executeQuery("select 1 from bank where No='"+txtNo.getText()+"' ");
boolean isPresent = rs1.next();
if(isPresent){
System.out.println("Already exists!!");
}
}
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
I hope this is not your final code, because there're several problems with it:
You're not managing your resources properly. Once you're done querying your database, you should consider closing your resultset, statement and connection objects.
Note that I checked whether the text in the JTextField is empty or not. This is a good way of preventing a call to the database when you know that the text field had no value in it.
I would suggest using a PreparedStatement rather than a Statement for querying to your database.
A ResultSet is initially positioned before the first row. So you need to call next() to move it to the next row (and check that it returns true) before you call one of the getXXX() methods.
JTextField input = new JTextField();
ArrayList < Integer > list = new ArrayList < Integer > ();
int integerv = Integer.parseInt(input.getText());
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/DB_name", "root", "yourpassword");
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("select column_name from table_name");
while (rs.next()) {
list.add(rs.getInt(1));
}
for (int a = 0; a < list.Size(); a++) {
if (a.get(a) == integerv) {
System.out.println("Match found");
break;
} else {
System.out.println("Match not found");
break;
}
}
} catch (Exception e) {
System.out.println("Error :" + e.getMessage());
}

Categories