proceed to next mySQL row JAVA - 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.

Related

want to return an rs.getInt() value in my database

I want to return an rs.getInt() value in this code snippet in my database. I really need it because I have to display the "User's score" in my Java Swing Simple Quiz Program, but it will always return 0 instead of what I want.
public int score() {
kon = koneksi.koneksiDb();
try {
st = kon.createStatement();
formLogin fl = new formLogin();
String sql = "SELECT score FROM user WHERE username = '" + fl.usr + "'";
rs = st.executeQuery(sql);
if (rs.next())
return rs.getInt(5);
} catch(SQLException e) {
JOptionPane.showMessageDialog(null, "Maaf, terjadi kesalahan.");
}
return 0;
}
My "score" column in the database is an integer.
Thanks to #DanielBarbardian and #deHaar in the comments. I tried return rs.getInt("score"); and it works. It'll return the score from the right column and display the right user's score.

How to use a same resultset twice in 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.

Issue With Cycling Through Entries In Database

I am attempting to go through my Access database with Java in order to check if a date range falls in between another date range to avoid duplicate reservations. I am running into an SQL error that says "ResultSet is Closed". I believe it is because I am using two resultSet in order to check two different dates withing one while loop. Here is the code:
String date1Query = "SELECT checkIn FROM Reservation WHERE roomLocation LIKE '" + room + "'";
String date2Query = "SELECT checkOut FROM Reservation WHERE roomLocation LIKE '" + room + "'";
ResultSet date1RS = statement.executeQuery(date1Query);
ResultSet date2RS = statement.executeQuery(date2Query);
while (date1RS.next()) {
date1 = date1RS.getDate("checkIn");
date2 = date2RS.getDate("checkOut");
dateCheckBool = dateCheck.dateCheck(date1, date2, checkIn, checkOut);
if (dateCheckBool == true)
break;
}
How else can I format this to achieve the same functionality (being able to check the input dates by the user against the already existing dates in the database) but not get an error? If this is not clear enough what I am trying to do I will try to clarify further upon request. Thank you!
EDIT: As requested here is the dateCheck code:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class dateCheck {
public boolean dateCheck(Date date1, Date date2, String date3, String
date4){
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date dateCheck1;
Date dateCheck2;
boolean dateRange1 = false;
boolean dateRange2 = false;
try {
dateCheck1 = dateFormat.parse(date3);
dateCheck2 = dateFormat.parse(date4);
if(dateCheck1.before(date1) || dateCheck1.after(date2))
dateRange1 = false;
else
dateRange1 = true;
if(dateCheck2.after(date2))
dateRange2 = false;
else
dateRange2 = true;
} catch (ParseException e) {
e.printStackTrace();
}
if(dateRange1 == false && dateRange2 == false)
return false;
else
return true;
}
}
Why fiddling around when SQL alone can give you the result?
If you wish to know whether a reservation is already in place, just ask the database.
SELECT id as result From reservations
Where (
([RoomLocation] like ?)
And (
(? between [checkin] and [checkout])
OR (? between [checkin] and [checkout])
)
);
in your java:
statement.setString(1,room);
statement.setDate(2,date1);
statement.setDate(3,date2);
..execution..
If there are any reservations you will receive the reservation id. If not null. You can also put above SQL within another select command and return true or false value.
If you are having issues with incompatible date formats, you might have to format the date and pass it as string.
Ps: answering from mobile, double check the SQL for typos.

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

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

Categories