Advertisement
Guest User

Untitled

a guest
May 19th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. package coderslab.dao;
  2.  
  3. import coderslab.entity.User;
  4.  
  5. import java.sql.*;
  6. import java.util.List;
  7.  
  8. public class MySqlUserDao implements UserDao{
  9.  
  10. private static final String FIND_ALL_USERS =
  11. "SELECT * FROM users";
  12. private static final String INSERT_USER_QUERY =
  13. "INSERT INTO users(name, surname, email, password) " +
  14. "VALUES (?,?,?,?)";
  15.  
  16. private final String jdbcUrl;
  17. private final String password;
  18. private final String user;
  19.  
  20. public MySqlUserDao(String jdbcUrl, String password, String user) {
  21. this.jdbcUrl = jdbcUrl;
  22. this.password = password;
  23. this.user = user;
  24. }
  25.  
  26. private Connection createConnection() throws SQLException {
  27. return DriverManager.getConnection(jdbcUrl,user,password);
  28. }
  29.  
  30. @Override
  31. public User insert(User user) {
  32. try(Connection connection = createConnection();
  33. PreparedStatement insertStm =
  34. connection.prepareStatement(INSERT_USER_QUERY,
  35. PreparedStatement.RETURN_GENERATED_KEYS)){
  36. insertStm.setString(1, user.getName());
  37. insertStm.setString(2, user.getSurname());
  38. insertStm.setString(3, user.getEmail());
  39. insertStm.setString(4, user.getPassword());
  40.  
  41. int result = insertStm.executeUpdate();
  42. if(result != 1){
  43. throw new RuntimeException("Execute updated returned " + result);
  44. }
  45. try(ResultSet generatedKeys = insertStm.getGeneratedKeys()){
  46. if(generatedKeys.first()){
  47. user.setId(generatedKeys.getInt(1));
  48. return user;
  49. }else{
  50. throw new RuntimeException("Generated key was not found");
  51. }
  52. }
  53. } catch (SQLException e) {
  54. throw new RuntimeException(e);
  55. }
  56. }
  57.  
  58. @Override
  59. public List<User> findAll() {
  60. return null;
  61. }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement