Exception occcured while finding Account via ID

Asked

Viewed 75 times

2

gave this error when trying to run a class

error Sef.module13.activity.Accountdaoexception: Exception occcured while finding Account via ID

that’s the class

package sef.module13.activity;
// Complete Code
public class AccountDAOException extends Exception{


    private static final long serialVersionUID = -2397012533045245997L;
    public static final String ERROR_FIND_ID="Exception occcured while finding Account via ID";
    public static final String ERROR_FIND_NAME="Exception occcured while finding Account via Name";
    public static final String ERROR_INSERT_ACCOUNT="Exception occured while inserting new Account";

    public AccountDAOException(String message, Throwable cause){
        super(message, cause);
    }

}

was while trying to run this class

package sef.module13.activity;


//Needs to be completed

public class AccountDAOClient {

    public static void main(String[] args) {
        AccountDAO obj = new AccountDAOImpl();

        try {

            obj.findAccount("John");
            // Test1 - Type code to test findAccount("1")

            obj.findAccount("Jane", "Doe");
            // Test2 - Type code to test findAccount("J","D"). How many records
            // do you get?

            // Test3 - Type code to test
            // insertAccount("6","Sasha","Kohli","[email protected]",90000)

            obj.insertAccount("6", "Sasha", "Kohli", "[email protected]",90000);

            // Test4 - Type code to test deposit("1",2000)
            obj.deposit("1", 2000);

            // Test5 - Type code to test deposit("2",3000)
            obj.deposit("2", 3000);

            // Test6 - Type code to test deleteAccount("6")

        } catch (Exception e) {
            System.out.println("erro " + e);
        }

    }
}

any suggestions?

I use the following interface

package sef.module13.activity;
// Complete Code
import java.util.List;

public interface AccountDAO {

    /**
     * Returns a list of accounts that with first names and last names that contain
     * the specified first name and last name.  The result list will be ordered via ID
     * in an ascending manner
     * 
     * @param firstName the first name of the account to search
     * @param lastName the last name of the account to search
     * @return list of accounts that match the criteria
     * 
     * @throws AccountDAOException when a problem occurs during search
     */
    public List findAccount(String firstName, String lastName) throws AccountDAOException;

    public Account findAccount(String id) throws AccountDAOException;

    public boolean insertAccount(String id, String firstName, String lastName, String email, float balance ) throws AccountDAOException;

    public boolean deposit(String id, float amount ) throws AccountDAOException;

    public boolean withdraw(String id, float amount ) throws AccountDAOException;

    public boolean deleteAccount(String id) throws AccountDAOException;
}

they are being implemented here the methods

package sef.module13.activity;

//Needs to be completed
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;

public class AccountDAOImpl implements AccountDAO {

    private Connection conn;

    public AccountDAOImpl() {


        String url = "jdbc:mysql://localhost/activity";
        String user = "root";
        String pass = "123";
        try{
        Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
        JOptionPane.showMessageDialog(null, "impossível carregar o Driver.");
        System.exit(0);
        }

        try {
            Connection cn = DriverManager.getConnection(url, user, pass);
            this.conn = cn;
            conn.setAutoCommit(false);
        } catch (SQLException sqle) {
        JOptionPane.showMessageDialog(null, "Problema ao conectar!");
        System.exit(0);
        }






//      String url = "jdbc:mysql://localhost/activity";
//      String user = "root";
//      String pass = "123";
//      
//      
//
//      try {
//          // 1 - Load the driver
//
//          // 2 - Obtain a connection using DriverManager class
//          Connection cn = DriverManager.getConnection(url, user, pass);
//          this.conn = cn;
//          conn.setAutoCommit(false);
//      } catch (SQLException e) {
//          // TODO Auto-generated catch block
//          e.printStackTrace();
//      }

        // } catch (ClassNotFoundException e) {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // } catch (SQLException e) {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }

    }

    // 3 - implement findAccount method which returns a list of accounts
    // matching the first name and last name combination
    public List findAccount(String firstName, String lastName)
            throws AccountDAOException {
        List<Account> results = new ArrayList<Account>();
        try {
            PreparedStatement pStmt = conn.prepareStatement("'select first_name from accout where first_name like  ?'");
            pStmt.setString(1, '%' + firstName.toUpperCase() + '%');
            pStmt.setString(2, '%' + lastName.toUpperCase() + '%');

            ResultSet rs = pStmt.executeQuery();
            while (rs.next()) {
                results.add(new AccountImpl(rs.getString(1), rs.getString(2),
                        rs.getString(3), rs.getString(4), rs.getFloat(5)));
            }

        } catch (SQLException e) {
            throw new AccountDAOException(AccountDAOException.ERROR_FIND_NAME,
                    e);
        }
        return results;
    }

    // 4 - Complete implementation for findAccount method
    public Account findAccount(String id) throws AccountDAOException {

        try {
            PreparedStatement pStmt = conn.prepareStatement("");
            pStmt.setString(1, id);
            ResultSet rs = pStmt.executeQuery();
            if (rs.next()) {
                return new AccountImpl(rs.getString(1), rs.getString(2),
                        rs.getString(3), rs.getString(4), rs.getFloat(5));
            }

        } catch (SQLException e) {
            throw new AccountDAOException(AccountDAOException.ERROR_FIND_ID, e);
        }

        return null;
    }

    // 5 - Complete implementation for insertAccount
    public boolean insertAccount(String id, String firstName, String lastName,
            String email, float balance) throws AccountDAOException {

        return false;
    }

    // 6 - Complete implementation for deposit. It should ensure that the
    // account balance is increased by the amount deposited.
    public boolean deposit(String id, float amount) throws AccountDAOException {
        return false;
    }

    // 7 - Complete implementation for withdraw. It should ensure that the
    // account balance is reduced by the amount deposited.
    public boolean withdraw(String id, float amount) throws AccountDAOException {
        return false;
    }

    // 8 - Complete implementation for deleteAccount
    public boolean deleteAccount(String id) throws AccountDAOException {
        return false;
    }

}

following the suggestion

I altered and put this line of code

try {

    obj.findAccount("John");
    // Test1 - Type code to test findAccount("1")

    obj.findAccount("Jane", "Doe");
    // Test2 - Type code to test findAccount("J","D"). How many records
    // do you get?

    // Test3 - Type code to test
    // insertAccount("6","Sasha","Kohli","[email protected]",90000)

    obj.insertAccount("6", "Sasha", "Kohli", "[email protected]",90000);

    // Test4 - Type code to test deposit("1",2000)
    obj.deposit("1", 2000);

    // Test5 - Type code to test deposit("2",3000)
    obj.deposit("2", 3000);

    // Test6 - Type code to test deleteAccount("6")

} catch (Exception e) {
    e.printStackTrace();/*essa linha >>>>>>>>>>>>>>*/
}

then he made that mistake

Sef.module13.activity.Accountdaoexception: Exception occcured while finding Account via ID at Sef.module13.activity.Accountdaoimpl.findAccount(Accountdaoimpl.java:110) at Sef.module13.activity.Accountdaoclient.main(Accountdaoclient.java:13) Caused by: java.sql.Sqlexception: Parameter index out of range (1 > number of Parameters, which is 0). at com.mysql.jdbc.SQLError.createSQLException(Sqlerror.java:1094) at com.mysql.jdbc.SQLError.createSQLException(Sqlerror.java:997) at com.mysql.jdbc.SQLError.createSQLException(Sqlerror.java:983) at com.mysql.jdbc.SQLError.createSQLException(Sqlerror.java:928) com.mysql.jdbc.PreparedStatement.checkBounds(Preparedstatement.java:3688) at com.mysql.jdbc.PreparedStatement.setInternal(Preparedstatement.java:3670) at com.mysql.jdbc.PreparedStatement.setString(Preparedstatement.java:4491) at Sef.module13.activity.Accountdaoimpl.findAccount(Accountdaoimpl.java:102) ... 1 more

which indicated those lines

Accountdaoimpl.java:110)

public Account findAccount(String id) throws AccountDAOException {

        try {
            PreparedStatement pStmt = conn.prepareStatement("'select first_name from accout where first_name like  ?'");
            pStmt.setString(1, id);                           
            ResultSet rs = pStmt.executeQuery();
            if (rs.next()) {
                return new AccountImpl(rs.getString(1), rs.getString(2),
                        rs.getString(3), rs.getString(4), rs.getFloat(5));
            }

        } catch (SQLException e) {
            throw new AccountDAOException(AccountDAOException.ERROR_FIND_ID, e);/*é essa linha>>>>>>>>>>>>>>>>>>>>>*/
        }

        return null;
    }

that Accountdaoclient.java:13 line)

try {

            obj.findAccount("John");/*essa linha>>>>>>>>>>>>>>>>>> */
            // Test1 - Type code to test findAccount("1")

            obj.findAccount("Jane", "Doe");
            // Test2 - Type code to test findAccount("J","D"). How many records
            // do you get?

            // Test3 - Type code to test
            // insertAccount("6","Sasha","Kohli","[email protected]",90000)

            obj.insertAccount("6", "Sasha", "Kohli", "[email protected]",90000);

            // Test4 - Type code to test deposit("1",2000)
            obj.deposit("1", 2000);

            // Test5 - Type code to test deposit("2",3000)
            obj.deposit("2", 3000);

            // Test6 - Type code to test deleteAccount("6")

        } catch (Exception e) {
            e.printStackTrace();
        }

that line (Accountdaoimpl.java:102)

public Account findAccount(String id) throws AccountDAOException {

        try {
            PreparedStatement pStmt = conn.prepareStatement("'select first_name from accout where first_name like  ?'");
            pStmt.setString(1, id);/*essa linha>>>>>>>>>>>>>>>>>>>>>*/                           
            ResultSet rs = pStmt.executeQuery();
            if (rs.next()) {
                return new AccountImpl(rs.getString(1), rs.getString(2),
                        rs.getString(3), rs.getString(4), rs.getFloat(5));
            }

        } catch (SQLException e) {
            throw new AccountDAOException(AccountDAOException.ERROR_FIND_ID, e);
        }

        return null;
    }
  • Instead of showing only the last line of the exception - System.out.println("erro " + e); - show exception entire - e.printStackTrace(); - otherwise it will be impossible to know what it is. Also, "mask" one exception in another (creating a AccountDAOException where the "real" exception - the SQLException - was relegated to "caused by") is a bad practice. Please do this, and post the complete exception, with all lines (chiefly the part that says "caused by...").

  • I put the changes can help me now?

  • 2

    Try to remove the simple quotation marks from your sql query. I’m not sure if this causes the error, but I know they are not necessary.

  • 1

    By the way, forget... After your editing everything I was writing lost its meaning... I suggest you read that related question, besides my suggestion above (i.e. not to mask one exception in the other). When to your mistake, most likely it is just that - the presence of quotation marks inside the quotation marks (the Prepared statement should be considering everything as a string, and so does not recognize that the query receives a parameter; when you try to pass the parameter, it complains of Parameter index out of range).

  • worked out thanks :)

1 answer

2

You should remove simple quotes from your SQL query:

PreparedStatement pStmt = 
    conn.prepareStatement("'select first_name from accout where first_name like  ?'");

Should stay:

PreparedStatement pStmt = 
    conn.prepareStatement("select first_name from accout where first_name like  ?");

If you quote, the statement does not understand your query, regardless of whether it has parameters or not.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.