1

Здравствуйте, помогите пожалуйста с неисправностью программы, получаю NullPointerException в строке preparedStatement = connection.prepareStatement(sql); подозреваю проблема в соединении, в методе getConn, но не уверен.

public class ProfileDAOImpl implements ProfileDAO {
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        public Connection getConn() throws Exception{
            Properties properties = new Properties();
            try {
                properties.load(new FileInputStream("info.properties"));
                String user = properties.getProperty("user");
                String password = properties.getProperty("password");
                String dburl = properties.getProperty("dburl");
                String driver = properties.getProperty("driver");
                Class.forName(driver);
                if (connection == null) {
                    connection = DriverManager.getConnection(user, password, dburl);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return connection;
        }
        private PreparedStatement getPreparedStatement(String sql) throws DAOException{
            if(preparedStatement == null) {
                try {
                    preparedStatement = connection.prepareStatement(sql);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            } return preparedStatement;
        }
        public void updateProfile(Profile profile) throws DAOException {
            String sql = "UPDATE profiles SET id=?, user_name=?," +
                    " nick_name=?, user_mail=?, password=?;";
            try {
                getPreparedStatement(sql);
                preparedStatement.setInt(1, profile.getId());
                preparedStatement.setString(2, profile.getUserName());
                preparedStatement.setString(3, profile.getNickName());
                preparedStatement.setString(4, profile.getUserMail());
                preparedStatement.setString(5, profile.getPassword());
                preparedStatement.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    public void closeConnection() {
        try {
            if (preparedStatement != null) {
                preparedStatement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

    public interface ProfileDAO {
    public void updateProfile(Profile profile) throws DAOException;
    public void closeConnection();
}

    public class Main {
    public static void main(String[] args) throws DAOException {
        ProfileDAO profileDAO = new ProfileDAOImpl();
        Profile profile = new Profile(2,"Test","Nick","test@test","123q");
        profileDAO.updateProfile(profile);
        profileDAO.closeConnection();
    }
}
3
  • Но ведь у вас в IDE есть дебаг? Почему не воспользуетесь им? 1 июн 2016 в 10:58
  • Конечно, у вас Connection будет null, ведь метод getConn() в котором происходит инициализация этого объекта, вы нигде не вызываете.
    – enzo
    1 июн 2016 в 11:36
  • Если вам дан исчерпывающий ответ, отметьте его как верный (галка напротив выбранного ответа). 2 июн 2016 в 5:41

1 ответ 1

2

Как уже отметили в комментариях вы не вызывайте метод getConn() - отсюда и NullPointerException.

Если у вас connection и preparedStatement всегда используются повторно, то лучше перенести их инициализацию в конструктор. Тогда ProfileDAOImpl получится такой:

public class ProfileDAOImpl implements ProfileDAO {
    final Connection connection;
    final PreparedStatement updateProfileStatement;

    public ProfileDAOImpl() throws Exception {
        Properties properties = new Properties();
        properties.load(new FileInputStream("info.properties"));
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String dburl = properties.getProperty("dburl");
        String driver = properties.getProperty("driver");
        Class.forName(driver);
        this.connection = DriverManager.getConnection(user, password, dburl);
        this.updateProfileStatement = connection.prepareStatement("UPDATE profiles SET id=?, user_name=?," +
                " nick_name=?, user_mail=?, password=?");
    }

    public void updateProfile(Profile profile) throws DAOException {
        try {
            updateProfileStatement.setInt(1, profile.getId());
            updateProfileStatement.setString(2, profile.getUserName());
            updateProfileStatement.setString(3, profile.getNickName());
            updateProfileStatement.setString(4, profile.getUserMail());
            updateProfileStatement.setString(5, profile.getPassword());
            updateProfileStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void closeConnection() {
        try {
            if (updateProfileStatement != null) {
                updateProfileStatement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
2
  • не задано поведение getConn так, чтобы выкидывать DAOE, как это правильно реализовать?
    – PolkovnikJ
    2 июн 2016 в 11:51
  • 1
    Если нужно выкидывать какое-то свое исключение то делается просто обертка, вот так: try { // тело метода } catch(Exception e) { throw new DAOException(e); }
    – Alex K
    6 июн 2016 в 13:05

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.