Здравствуйте, помогите пожалуйста с неисправностью программы, получаю 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();
}
}
Connection
будетnull
, ведь методgetConn()
в котором происходит инициализация этого объекта, вы нигде не вызываете.