I've got the following code to query a database! But the code inside the while loop doesn't get executed! No messagebox, just doesn't get executed! Can anyone help me! Result set is not empty! When I print the same value out of the try catch block it gets executed and the right values get printed! Th DB connection is a standard MySQL DB connection class!
database = new DBConnection();
String dept = txtSearch.getText();
String Query = "SELECT * FROM department where dept_name= '" + dept + "'";
ResultSet set = database.queryDatabase(Query);
try {
if (set.next() == false) {
JOptionPane.showMessageDialog(null, "No Matchs found for the search query! Try Again.", "Search Error", JOptionPane.ERROR_MESSAGE);
} else {
while (set.next()) {
System.out.print(set.getString("dept_name"));
txtName.setText(set.getString("dept_name"));
txtDes.setText(set.getString("dept_desc"));
}
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), ex.getCause().toString(), JOptionPane.ERROR_MESSAGE);
}
You're throwing out the first row of your query by calling set.next() and then ignoring the data in the row here:
if (set.next() == false) { // ***** here on this line
JOptionPane.showMessageDialog(null, "No Matchs found for the search query!
Try Again.", "Search Error", JOptionPane.ERROR_MESSAGE);
} else {
while (set.next()) {
System.out.print(set.getString("dept_name"));
txtName.setText(set.getString("dept_name"));
txtDes.setText(set.getString("dept_desc"));
}
}
Instead be sure to extract information from your ResultSet every time you call next() and it returns true.
You could do something like this instead:
int setCount = 0;
while (set.next()) {
setCount++;
System.out.print(set.getString("dept_name"));
txtName.setText(set.getString("dept_name"));
txtDes.setText(set.getString("dept_desc"));
}
if (setCount == 0) {
// show a warning to the user that the result set was empty
}
Related
I have MySQL database having columns named with roomno, availability, clean_status, price and room_type. Column Availability has data as either 'available' or 'not available' and column clean_status has data as either 'dirty' or 'cleaned'. I am trying to fetch data from database and if the selected room is either 'not available' or 'dirty', I would like to show error message stating 'room should be available or cleaned before adding customer'. I have used ResultSet and execute the work. Earlier it showed the error message. I modified the code and made it executable, but it doesn't give any error message neither the data in column of database has changed. I think it is because of ResultSet. Can any body help me?
try {
connection = new MySQLConnection();
} catch (Exception ae) {
if (ae != null) {
JOptionPane.showMessageDialog(null, "Error Connection To Database");
}
}
String avai ="select availability from rooms where roomno='"+roomno+"'";
String clean ="select clean_status from rooms where roomno='"+roomno+"'";
try {
this.see = connection.s.executeQuery(clean);
}
catch (SQLException ex) {
ex.printStackTrace();
}
try {
this.conn = new MySQLConnection();
this.se = connection.s.executeQuery(avai);
} catch (SQLException ex) {
ex.printStackTrace();
}
if (se.equals("Available") && see.equals("Cleaned")){
String str = "insert into customer values('" +id + "','" +mobileno +"','" +name +"','" +gender+"','"+country+"','" +roomno+"','"+checkedin+"','" +deposit+"')";
try {
connection.s.executeUpdate(str);
JOptionPane.showMessageDialog(null, "Data Added To Database");
}
catch (Exception eu) {
eu.printStackTrace();
JOptionPane.showMessageDialog(this, "Error In Database Table", "Message", JOptionPane.ERROR_MESSAGE);
}
}
else if (se.equals("Not Available") || see.equals("Dirty")){
JOptionPane.showMessageDialog(null,"Room Is Dirty or Not Available");
}
From your code se acd see are the respective ResultSet obtained, I am not sure how ResultSet.equals works, but I suggest you use the following
while(see.next())
{
String clean=see.getString("clean_status");
}
while(se.next())
{
String avail=see.getString("availability");
}
And then check the output.
However,if the error still persists, check in the table if the values for availability and clean_status are having any leading or trailing spaces, which could be an issue at times.
I got a method that deletes a record in the database when inserting a tag value. when a record is deleted, a message in the console screen pops up saying "this record has been deleted ". It works fine when inserting a valid tag value. However, when I insert an invalid tag value that doesn't exist in my database it acts like it has deleted it and displays that previous message. Although within my method says if the outcome is not equal 1 (which is not true) return false, but it's apparently not validating the inserted data. Can anyone tell me what's the problem
public boolean DeleteWallet(String Tag) throws SQLException {
System.out.println("Deleting wallet");
Connection dbConnection = null;
Statement statement = null;
int result = 0;
String query = "DELETE FROM wallets WHERE Tag = '" + Tag + "';";
try {
dbConnection = getDBConnection();
statement = dbConnection.createStatement();
System.out.println("The record has been deleted successfully");
// execute SQL query
result = statement.executeUpdate(query);
} finally {
if (statement != null) {
statement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
if (result == 1) {
return true;
} else {
return false;
}
}
The statement
System.out.println("The record has been deleted successfully");
is being printed before you actually perform any database operations statement.executeUpdate(query);
Instead, you should perform your database operation within your try statement, then print your success output. If the statement fails (IE an exception is thrown) the success statement will be skipped.
Additionally, instead of relying on the output the the executeUpdate(query) to determine if your query was successful, I would always assume your query or some operation before the query fails, and only return true if all database processing was successful.
Finally, the use of prepared statements will help make your query easier to read, use, and is better secured against SQLInjection attacks.
Example:
public class DatabaseOperations {
public boolean DeleteWallet(String Tag) {
//Query used for prepared statement
static final String DELETE_QUERY = "DELETE FROM wallets WHERE Tag=?";
System.out.println("Attempting to delete wallet using query:" + DELETE_QUERY);
//assume DELETE operation fails due to exection at any stage
Boolean result = false;
try (
//Objects that can automatically be closed at the end of the TRY block
//This is known as AutoCloseable
Connection dbConnection = getDBConnection();
PreparedStatement statment = dbConnection.preparedStatement(DELETE_QUERY))
{
//replace ? with Tag
statement.setString(1, Tag);
int row = preparedStatement.executeUpdate();
//If statement fails skip to catch block
result = true;
System.out.println("The record in row " + row + " has been deleted successfully");
} catch (SQLException sqle) {
//likely thrown due to "Record Not Found"
//TODO investigate further for the specific exception thrown from the database implementation you are using.
//TODO print helpful message to help user of this method resolve this issue
} catch (Exception) {
//TODO handle any other exceptions that may happen
}
return result;
}
}
I wanted an error to popup, when the user entered a wrong id into the delete field. But even if a wrong id is entered, the query still proceeds, but no data is deleted. Here's my code:
String value = jTextField19.getText();
if (value == null || "".equals(value)) {
JOptionPane.showMessageDialog(null, "The field is blank!");
} else {
theQuery("DELETE FROM inventorydb WHERE item_id=('"+jTextField19.getText()+"') AND item_id IS NOT NULL");
}
The theQuery method:
private void theQuery(String query) {
Connection con = null;
Statement st = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/inventory", "root", "");
st = con.createStatement();
st.executeUpdate(query);
JOptionPane.showMessageDialog(null, "Done!");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null,"Error!");
}
}
First of all: do not ever directly build SQL queries from user input, use prepared statements instead. If you don't know about SQL Injection, you should.
If you are using JDBC, you can check the result of #executeUpdate() to see how many rows were affected. If it was zero, then you can say that it was a wrong id.
This is the method definition:
public int executeUpdate(java.lang.String sql)
The return value is:
An int that indicates the number of rows affected, or 0 if using a DDL statement.
In the program at hand, you can just simply do this:
int deleted = st.executeUpdate(query);
if (deleted == 0) {
JOptionPane.showMessageDialog(null, "Nothing to delete!");
return;
}
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 = ?
I am developing a project for Online Banking System. I want to retrieve a data from database using JDBC. However, it is showing Exhausted result exception though the query is returning a row in SQLPlus. Please Help. Here's the Code:
try
{
Class.forName("oracle.jdbc.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:orcl", "hr", "XXXXXX");
String pass = 'sid';
String user = 'sid';
String accountnumber = '2345';
String sql = "select * from user_info where account_number=?";
s1 = con.prepareStatement(sql);
s1.setString(1,accountnumber);
rs1 = s1.executeQuery(sql);
rs1.next();
if(user.equals(rs1.getString("user_name")))
{
if(pass.equals(rs1.getString("password")))
{
if(accountnumber.equals(rs1.getString("account_number")))
{
new AccountInformation(accountnumber).setVisible(true);
}
else
{
JOptionPane.showMessageDialog(this, "Account Number is Incorrect");
}
}
else
{
JOptionPane.showMessageDialog(this, "Password is Incorrect");
}
}
else
{
JOptionPane.showMessageDialog(this, "User Name is Incorrect");
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this,e);
}
You threw away your bind parameter when you passed the SQL to Statement#executeQuery - use this one from PreparedStatement...
rs1=s1.executeQuery();
// rs1=s1.executeQuery(sql);
// check if you got a row
if (rs1.next()) {
// as before....
}