1

Здравствуйте, необходимо сделать одно DAO, и в нём 2 PreparedStatement (для каждого из методов), один я создаю и использую, а второй не выходит, при условии что закрытие должно происходить 1 раз, и методы должны чередоваться в цикле 5 раз, т.е. необходимо сделать следующее: создать по полю для каждого метода, при вызове метода поле инициализировать, при последующих вызовах - использовать уже инициализированное значение, все поля закрыть в одном методе, в конце работы. как это реализовать? помогите пожалуйста

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

public void getConn() throws DAOException {
    try (FileReader reader = new FileReader("db.properties")) {
        Properties properties = new Properties();
        properties.load(reader);
        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(dburl, user, password);
        }
    } catch (IOException e) {
        throw new DAOException("file error ",e);
    } catch (ClassNotFoundException e) {
        throw new DAOException("class error ",e);
    } catch (SQLException e) {
        throw new DAOException("conn error ",e);
    }
}
private PreparedStatement getPreparedStatement(String sql) throws DAOException{
    if(preparedStatement == null) {
        try {
            preparedStatement = connection.prepareStatement(sql);
        } catch (Exception e) {
            throw new DAOException("create ps error ",e);
        }
    } return preparedStatement;
}
@Override
public void updateProfile(Profile profile) throws DAOException {
    String sql = "UPDATE Profile SET user_name=?," +
            " nick_name=?, user_mail=?, password=? WHERE id=?";
    try {
        getPreparedStatement(sql);
        preparedStatement.setString(1, profile.getUserName());
        preparedStatement.setString(2, profile.getNickName());
        preparedStatement.setString(3, profile.getUserMail());
        preparedStatement.setString(4, profile.getPassword());
        preparedStatement.setInt(5, profile.getId());
        preparedStatement.executeUpdate();
    } catch (Exception e) {
        throw new DAOException("update error ",e);
    }
}
@Override
public void close() throws DAOException{
    try {
        if (preparedStatement != null) {
            preparedStatement.close();
            preparedStatement = null;
        }
    } catch (Exception e) {
        throw new DAOException("Close (ps) error ",e);
    }
    try {
        if (connection != null) {
            connection.close();
            connection = null;
        }
    } catch (Exception e) {
        throw new DAOException("Close (conn) error",e);
    }
}
@Override
public void createProfile (Profile profile) throws DAOException {
    String sql = "INSERT INTO Profile (user_name, nick_name, user_mail, password) " +
            "VALUES (?,?,?,?)";
    try {
        getPreparedStatement(sql);
        preparedStatement.setString(1, profile.getUserName());
        preparedStatement.setString(2, profile.getNickName());
        preparedStatement.setString(3, profile.getUserMail());
        preparedStatement.setString(4, profile.getPassword());
        preparedStatement.executeUpdate();

    } catch (Exception e) {
        throw new DAOException("create error ",e);
    }
}

}

собственно необходимо чуть переписать метод main

public class Main {
public static void main(String[] args) {

    ProfileDAO profile = new ProfileDAOImpl(); 
    Profile Test = new Profile();
    Test.setUserName("Proverka");
    Test.setNickName("test");
    Test.setUserMail("@gmail.com");
    Test.setPassword("qwerty");
    Test.setId(2);

    try {
        profile.getConn();
        for (int i = 0; i < 5; i++) {
            profile.updateProfile(Test);
            profile.createProfile(Test);
        }
        profile.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

1 ответ 1

1

Накидал примерный вариант:

public class ProfileDAOImpl {
    private Connection connection = null;
    private Map<String, PreparedStatement> preparedStatements = new HashMap<String, PreparedStatement>();

    public void getConn() throws Exception {
        try(FileReader reader = new FileReader("db.properties")) {
            Properties properties = new Properties();
            properties.load(reader);
            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(dburl, user, password);
            }
        } catch(IOException e) {
            throw new Exception("file error ", e);
        } catch(ClassNotFoundException e) {
            throw new Exception("class error ", e);
        } catch(SQLException e) {
            throw new Exception("conn error ", e);
        }
    }

    private PreparedStatement getPreparedStatement(String sql) throws Exception {
        PreparedStatement preparedStatement = preparedStatements.get(sql);
        if(preparedStatement == null) {
            try {
                preparedStatement = connection.prepareStatement(sql);
                preparedStatements.put(sql, preparedStatement);
            } catch(Exception e) {
                throw new Exception("create ps error ", e);
            }
        }
        return preparedStatement;
    }

    public void updateProfile(Profile profile) throws Exception {
        String sql = "UPDATE Profile SET user_name=?," +
            " nick_name=?, user_mail=?, password=? WHERE id=?";
        try {
            PreparedStatement preparedStatement = getPreparedStatement(sql);
            preparedStatement.setString(1, profile.getUserName());
            preparedStatement.setString(2, profile.getNickName());
            preparedStatement.setString(3, profile.getUserMail());
            preparedStatement.setString(4, profile.getPassword());
            preparedStatement.setInt(5, profile.getId());
            preparedStatement.executeUpdate();
        } catch(Exception e) {
            throw new Exception("update error ", e);
        }
    }

    public void close() throws Exception {
        for(PreparedStatement preparedStatement : preparedStatements.values()) {
            try {
                if(preparedStatement != null) {
                    preparedStatement.close();
                }
            } catch(Exception e) {
                throw new Exception("Close (ps) error ", e);
            }
        }
        preparedStatements = null;
        try {
            if(connection != null) {
                connection.close();
                connection = null;
            }
        } catch(Exception e) {
            throw new Exception("Close (conn) error", e);
        }
    }

    public void createProfile(Profile profile) throws Exception {
        String sql = "INSERT INTO Profile (user_name, nick_name, user_mail, password) " +
            "VALUES (?,?,?,?)";
        try {
            PreparedStatement preparedStatement = getPreparedStatement(sql);
            preparedStatement.setString(1, profile.getUserName());
            preparedStatement.setString(2, profile.getNickName());
            preparedStatement.setString(3, profile.getUserMail());
            preparedStatement.setString(4, profile.getPassword());
            preparedStatement.executeUpdate();

        } catch(Exception e) {
            throw new Exception("create error ", e);
        }
    }
}

В коде заменил DAOException на Exception, чтобы было удобнее в Eclipse'е писать.

В новом варианте PreparedStatement сохраняются в карту, в которой ключ - это и есть сам запрос. В результате для разных запросов getPreparedStatement возвращает разные PreparedStatement, а не один и тот же как раньше. Вместо всего запроса в ключе можно использовать его хеш-сумму.

Также рекомендую сразу применять интерфейс Closeable, чтобы не забыть закрыть DAO после использования.

2
  • благодарю, а можно допустим как то без map реализовать то что я описал выше? (если с map, то методы update и прочее требует иного указания PreparedStatement, в поле он инициализирован с map)
    – PolkovnikJ
    9 июн 2016 в 11:55
  • Можно в методе getPreparedStatement не возвращать preparedStatement, а присваивать полю preparedStatement (добавить такое поле в класс). Но это как-то костыльно.
    – slava
    9 июн 2016 в 12:07

Ваш ответ

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

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