This code to search for a book or a user within databases, there is no problem when you search for a user, but when you search for a book that does not exist, it appears this error:
Error: After end of result set
if(RB1.isSelected()==true)
{
Statement stmt = (Statement)conn.createStatement();
String SQL1 = "select * from usernames";
ResultSet rs1 = stmt.executeQuery(SQL1);
String ID ="";
while(rs1.next())
{
ID = rs1.getString("UserID");
if(UIorBItf.getText().compareTo(ID) == 0)
{
JOptionPane.showMessageDialog(null,rs1.getString("Full_Name") +
" is available","Query result",JOptionPane.INFORMATION_MESSAGE);
break;
}
}
if(UIorBItf.getText().compareTo(ID) != 0)
{
JOptionPane.showMessageDialog(null, UIorBItf.getText() +" is
not available","Query result",JOptionPane.INFORMATION_MESSAGE);
}
}
if(RB2.isSelected()==true)
{
//JOptionPane.showMessageDialog(null, UIorBItf.getText() +" Now
//You are inside Book search","Query result",JOptionPane.INFORMATION_MESSAGE);
Statement stmt2= (Statement)conn.createStatement();
String SQL2 = "select * from books";
ResultSet rs2 = stmt2.executeQuery(SQL2);
String ID ="";
while(rs2.next())
{
ID = rs2.getString("BookID");
if(ID.compareTo(UIorBItf.getText()) ==0)
{
JOptionPane.showMessageDialog(null,rs2.getString("Book_Name") +
" is available","Query result",JOptionPane.INFORMATION_MESSAGE);
break;
}
}
if(UIorBItf.getText().compareTo(ID)!=0)
{
JOptionPane.showMessageDialog(null,rs2.getString("Book_Name") +
" is not available","Query result",JOptionPane.INFORMATION_MESSAGE);
}
}
}catch(Exception e)
{
System.out.println("Error: " + e.getMessage());
}
if(UIorBItf.getText().compareTo(ID)!=0)
{
// problem is here
// from other code I am guessing you want UIorBItf.getText()
// instead of rs2.getString("Book_Name")
JOptionPane.showMessageDialog(null,rs2.getString("Book_Name") +
" is not available","Query result",JOptionPane.INFORMATION_MESSAGE);
}
The problem is here:
if(UIorBItf.getText().compareTo(ID)!=0)
{
JOptionPane.showMessageDialog(null,rs2.getString("Book_Name") +
" is not available","Query result",JOptionPane.INFORMATION_MESSAGE);
}
You can't call rs2.getString("Book_Name") from here, since you only end up here when the while loop is finished. At this point you will already have moved past the last line since rs2.next() has returned false.
You cannot call
rs2.getString("Book_Name")
if rs2.next()
doesnt match anything from your query
select * from books
Related
I've been trying to solve this issue for the past couple of days. I have a SerachUser function where I input all the data like age, gender, city and interests into each string and check them into a select query command.
If data is present, I print them out.
Unfortunately the search isn't working completely. For eg: my table user doesn't have 'F' gender. But if I type 'F' I still get data instead of displaying "ResultSet in empty in Java".
Below is a brief code I have done.
try{
conn = DriverManager.getConnection(DB_URL,"shankarv5815","1807985");
st = conn.createStatement();
rs = st.executeQuery("Select loginID, f_name, l_name from users where gender = '" +
searchUser.getGender() + "' and age between '" + min + "' and '" + max + "' and city = '" +
searchUser.getCity() + "' and interest1 = '" + searchUser.getInterest1() +
"' or interest2 = '" + searchUser.getInterest1() + "' or interest3 = '" +
searchUser.getInterest1() + "' and loginID != '" + curUser + "'");
if (rs.next() == false) {
System.out.println("ResultSet in empty in Java");
}
else {
do {
String id = rs.getString(1);
String fName = rs.getString(2);
String lName = rs.getString(3);
System.out.print(id +" ," + fName + ", " + lName);
System.out.println();
} while (rs.next());
}
}
catch(SQLException e){
e.printStackTrace();
}
finally
{
try
{
conn.close();
st.close();
rs.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
A reduced version of your query is :
Select * from users
Where gender = 'F'
And interest1 = 'FISHING'
Or interest2 = 'FISHING'
However, AND has higher priority than OR, so this query is equivalent to :
Select * from users
Where ( gender = 'F' And interest1 = 'FISHING')
Or interest2 = 'FISHING'
What you need to do is add brackets, so :
Select * from users
Where gender = 'F'
And ( interest1 = 'FISHING' Or interest2 = 'FISHING')
By the way, you are also leaving yourself wide open to a SQL injection attack, by including the search terms directly in the SELECT statement ( see What is SQL injection? ).
Much better would be to get in the habit of always using a PreparedStatement.
I have an SQLite database with different car types. Currently my query is only returning the first car type that the user enters. For example, if the user enters "Nissan", the program currently returns the first Nissan it finds even though there are several Nissans in the database.
How can I optimize the below code to return all the Nissans in the database?
static void databaseaccess() {
Scanner reader = new Scanner(System.in);
String newreader = reader.nextLine();
try {
Class.forName("org.sqlite.JDBC");
} catch (Exception e) {
System.out.println("Exception 1: " + e);
}
Connection d = null;
try {
d = DriverManager.getConnection("jdbc:sqlite:/fake/carmart.db");
}catch (SQLException s) {
System.out.println("Exception 2:" + s);
}
String sql = "select * from selling WHERE cartype = " + "'" + newreader + "'";
PreparedStatement p = null;
ResultSet r = null;
try{
p = d.prepareStatement(sql);
p.clearParameters();
r = p.executeQuery();
String cartype;
String carlocation;
String carprice;
while (r.next()) {
carlocation = r.getString("carlocation");
carprice = r.getString("carprice");
cartype = r.getString("cartype");
System.out.println("This car is located in "
+ carlocation
+ " and currently sells for $" + carprice);
}
}
}
I want to add new room, I would type the room details, Room Number, Room type, Bed number and Rates into the text fields, when I click save, I get the error java.lang.NumberFormatException: For input string: ""
The error originates from at RoomMang.jButton1ActionPerformed(RoomMang.java:352) which is fetchFromTextF(); function. See Image :
My insert statement using System.out.println (insertquery); looks like this:
insert into roomdetail(room_no,room_type,room_rate,room_bed)values('','','','');
This is how i fetch the data from the textfields:
public void fetchFromTextF(){
rno=rnumber.getText();
rtype=jTextField2.getText();
rrate=Integer.parseInt(jTextField3.getText());
rbed=jTextField4.getText();
}
And this is my save action performed button:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
clearTextF();
enableTextF();
String query = "SELECT * FROM roomdetail where room_no like '" + rnumber.getText() + "';";
smt = con.createStatement();
rs1 = smt.executeQuery(query);
if (!rs1.next()) {
try {
if (evt.getActionCommand().equals("Save")) {
fetchFromTextF();
int code = JOptionPane.showConfirmDialog(this, "Information of Room No." +rno+ " will be added in database.", "Confirmation", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
if (code == JOptionPane.YES_OPTION) {
String insertquery = "insert into roomdetail(room_no,room_type,room_rate,room_bed)values('" +rno + "','" + rtype + "'," + rrate + ",'" + rbed + "');";
smt = con.createStatement();
int success = smt.executeUpdate(insertquery);
if (success > 0) {
JOptionPane.showMessageDialog(this, "Record Saved");
jButton1.setText("New");
} else {
JOptionPane.showMessageDialog(this, "Problem in Saving. Retry");
}
} else {
}
} else if (evt.getActionCommand().equals("New")) {
clearTextF();
jButton1.setText("Save");
}
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(this, "Room No. already used, Give another Room No.");
}
} catch (Exception ex) {
}
}
The value in jTextField3 is blank so the below will fail
rrate=Integer.parseInt(jTextField3.getText());
maybe change to
rrate = -1;
if (jTextField3.getText().trim().length() > 0) {
rrate=Integer.parseInt(jTextField3.getText());
}
or simply catch the exception
try {
rrate=Integer.parseInt(jTextField3.getText().trim ());
}
catch (NumberFormatException ex) {
System.err.println (ex);
rrate = -1;
}
I have the following function and I am trying to compare the number of students enrolled in a class with the class max. If the number enrolled is greater than the class max, I want to return a message that says, "The Class if Full".
public static void classFullCheck() {
try {
String currentNumberInClassAsString = ("SELECT class_id, COUNT(*) FROM ClassSelector.student_x_class WHERE class_id = " + selectedClass);
rs = myStmt.executeQuery(currentNumberInClassAsString);
int currentNumberInClassAsInt = 0;
if(rs.next()){
currentNumberInClassAsInt = rs.getInt(1);
}
String classSizeAsString = ("SELECT class_size FROM ClassSelector.classes WHERE class_id = " + selectedClass);
rs = myStmt.executeQuery(classSizeAsString);
int classSizeAsInt = 0;
if(rs.next()){
classSizeAsInt = rs.getInt("class_size");
}
if (currentNumberInClassAsInt > classSizeAsInt){
System.out.println("Sorry, this class is Full!");
}
} catch (java.sql.SQLException SQL) {
SQL.printStackTrace();
}
}
I am inserting the classFullcheck() function into the addClass() function like this:
public static void addClass() {
try {
rs = myStmt.executeQuery("SELECT * FROM ClassSelector.classes");
while (rs.next()) {
String availableClasses = rs.getString("class_id") + "\t" + rs.getString("class_name") + "\t" + rs.getString("description");
System.out.println(availableClasses);
}
System.out.println("Enter Class ID from Classes Listed Above to Join: ");
selectedClass = sc.nextLine();
rs = myStmt.executeQuery("SELECT * FROM ClassSelector.classes WHERE class_id = " + selectedClass);
while (rs.next()) {
classFullCheck();
String innerJoin = (userEnterIdAsName + " has been added to " + rs.getString("class_name") + " " + rs.getString("class_id"));
System.out.println(innerJoin);
String student_x_classJoin = "INSERT INTO student_x_class" + "(student_id, student_name, class_id, class_name)" + "VALUES (?, ?, ?, ?)";
PreparedStatement pStmt = con.prepareStatement(student_x_classJoin);
pStmt.setString(1, user_entered_student_id);
pStmt.setString(2, userEnterIdAsName);
pStmt.setString(3, rs.getString("class_id"));
pStmt.setString(4, rs.getString("class_name"));
pStmt.executeUpdate();
System.out.println("Would you like to enroll " + userEnterIdAsName + " into another class? (Y/N)");
String addAdditionalClass = sc.nextLine();
if (addAdditionalClass.equalsIgnoreCase("Y")) {
addClass();
} else if (addAdditionalClass.equalsIgnoreCase("N")) {
return;
}
}
}
catch (java.sql.SQLException SQL) {
System.out.println("Wait, This Student is already enrolled in this class!");
}
}
I am currently just getting both messages printed out, even if a class is not full. Any suggestions would help a lot.
if (currentNumberInClassAsInt >= classSizeAsInt) {
String updateStatus = "Update ClassSelector.classes SET status = ? WHERE class_id = " + selectedClass;
PreparedStatement pStmt = con.prepareStatement(updateStatus);
pStmt.setString(1, "Closed");
pStmt.executeUpdate();
System.out.println("Sorry, this class is Full! Select a different Class:");
System.out.println("\nSign Up For a Class\n");
addClass();
}
I think you want this:
currentNumberInClassAsInt = rs.getInt(2);
instead of:
currentNumberInClassAsInt = rs.getInt(**1**);
I don't think the ResultSet is 0 based...
Also is rs a global variable because it looks like you are changing your ResultSet rs when you call classFullCheck(). You may not have what you think you do in the ResultSet...
rs = myStmt.executeQuery("SELECT * FROM ClassSelector.classes WHERE class_id = " + selectedClass);
while (rs.next()) {
classFullCheck();//****************result set changed here******************
String innerJoin = (userEnterIdAsName + " has been added to " + rs.getString("class_name") + " " + rs.getString("class_id"));
You may think you have this: rs = myStmt.executeQuery("SELECT * FROM ClassSelector.classes WHERE class_id = " + selectedClass); in your result set but you change rs in classFullCheck(). You may want to store the data in a different object that way when you run another query you can still access the data.
As the title says. I have trouble in Returning a value that says "Not Found",
When i try to input a value that is not in range.
PS: I'm new here so be gentle. hehe
public static void checkStatus(String ID_No) throws SQLException{
try{
ResultSet rs;
String validStatus = "SELECT * FROM validation";
st = connection.createStatement();
rs = st.executeQuery(validStatus);
while(rs.next()){
getStudValid = rs.getString("ID_No");
getValidStatus = rs.getString("Validation");
if (!getValidStatus.equals("Accepted") && getStudValid.equals(ID_No)){
System.out.println("Student " + getStudValid + " Please complete the required pre-requisite processes.");
} else if (getValidStatus.equals("Accepted") && getStudValid.equals(ID_No)){
System.out.println("Student " + getStudValid + " You are Enrolled!");
}
}
rs.close();
} catch(SQLException e){
System.out.println("Updated "+ ID_No);
}
}
Take that if-else condition in a method which returns a String "NOT FOUND".
Change
public static void checkStatus(String ID_No) throws SQLException{
to
public static String checkStatus(String ID_No) throws SQLException{
then return a String whether successful or "Not Found"
So, essentially when rs.next holds, then that means that there is some sort of value that is found when the query is executed.
RS.next returns a boolean, and using that boolean you can do something like this.
boolean isFound = rs.next();
if(isFound)
{
// your while loop
// at the end of your while loop add isFound = rs.next()
}
else
{
return "Not Found";
}
It depends on what you want to happen when a student is not found here is 2 ways you could do it.
Throw an exception (this would be if it is an error if a student doesnt exist)
try {
checkStatus("studentA");
} catch(StudentNotFoundException e) {
System.out.println("Student wasnt found!");
}
public static void checkStatus(String ID_No) throws SQLException, StudentNotFoundException {
try{
ResultSet rs;
String validStatus = "SELECT * FROM validation";
st = connection.createStatement();
rs = st.executeQuery(validStatus);
while(rs.next()){
getStudValid = rs.getString("ID_No");
getValidStatus = rs.getString("Validation");
if (!getValidStatus.equals("Accepted") && getStudValid.equals(ID_No)){
System.out.println("Student " + getStudValid + " Please complete the required pre-requisite processes.");
return;
} else if (getValidStatus.equals("Accepted") && getStudValid.equals(ID_No)){
System.out.println("Student " + getStudValid + " You are Enrolled!");
return;
}
}
throw new StudentNotFoundException(); // create this exception eg: class StudentNotFoundException extends Exception
rs.close();
} catch(SQLException e){
System.out.println("Updated "+ ID_No);
}
}
Or you could return a value
int exists = checkStatus("studentA");
if(exists == 0)
System.out.println("Student wasnt found");
public static int checkStatus(String ID_No) throws SQLException{
try{
ResultSet rs;
String validStatus = "SELECT * FROM validation";
st = connection.createStatement();
rs = st.executeQuery(validStatus);
while(rs.next()){
getStudValid = rs.getString("ID_No");
getValidStatus = rs.getString("Validation");
if (!getValidStatus.equals("Accepted") && getStudValid.equals(ID_No)){
System.out.println("Student " + getStudValid + " Please complete the required pre-requisite processes.");
return 1; // found
} else if (getValidStatus.equals("Accepted") && getStudValid.equals(ID_No)){
System.out.println("Student " + getStudValid + " You are Enrolled!");
return 1; // found
}
}
return 0; // no student found
rs.close();
} catch(SQLException e){
System.out.println("Updated "+ ID_No);
return -1; // error occured
}
}
You could develop logic like -
boolean found = false;
while(rs.next()){
getStudValid = rs.getString("ID_No");
getValidStatus = rs.getString("Validation");
if(getStudValid.equals(ID_No)){
if(getValidStatus.equals("Accepted"))
System.out.println("Student " + getStudValid + " You are Enrolled!");
else
System.out.println("Student " + getStudValid + " Please complete the required pre-requisite processes.");
found =true;
}
}
if(!found)
System.out.println("Student "+ID_No+" Not found");
But I'd recommend you to optimize this code by optimizing your query - SELECT * FROM validation where ID_No=? and also use PrepareStatement.
String validStatus = "SELECT * FROM validation where ID_No=?";
pst = connection.prepareStatement(validStatus);
pst.setString(1,Id_No);
rs = pst..executeQuery();
if(rs.next()){
if(getValidStatus.equals("Accepted"))
System.out.println("Student " + getStudValid + " You are Enrolled!");
else
System.out.println("Student " + getStudValid + " Please complete the required pre-requisite processes.");
}else
System.out.println("Student "+ID_No+" Not found");
Some related topics -
Difference between Statement and PreparedStatement