|
| 1 | +package com.stackify.daos; |
| 2 | + |
| 3 | +import java.sql.Connection; |
| 4 | +import java.sql.PreparedStatement; |
| 5 | +import java.sql.ResultSet; |
| 6 | +import java.sql.SQLException; |
| 7 | +import java.util.ArrayList; |
| 8 | +import java.util.List; |
| 9 | + |
| 10 | +import org.apache.logging.log4j.LogManager; |
| 11 | +import org.apache.logging.log4j.Logger; |
| 12 | + |
| 13 | +import com.stackify.models.User; |
| 14 | +import com.stackify.utils.ConnectionUtil; |
| 15 | + |
| 16 | +public class UserDAO { |
| 17 | + |
| 18 | + private Logger logger = LogManager.getLogger(UserDAO.class); |
| 19 | + |
| 20 | + public void createTable() { |
| 21 | + try (Connection con = ConnectionUtil.getConnection()) { |
| 22 | + String createQuery = "CREATE TABLE IF NOT EXISTS users(email varchar(50) primary key, name varchar(50))"; |
| 23 | + PreparedStatement pstmt = con.prepareStatement(createQuery); |
| 24 | + |
| 25 | + pstmt.execute(); |
| 26 | + } catch (SQLException exc) { |
| 27 | + logger.error(exc.getMessage()); |
| 28 | + } |
| 29 | + |
| 30 | + } |
| 31 | + |
| 32 | + public void add(User user) { |
| 33 | + try (Connection con = ConnectionUtil.getConnection()) { |
| 34 | + |
| 35 | + String insertQuery = "INSERT INTO users(email,name) VALUES(?,?)"; |
| 36 | + PreparedStatement pstmt = con.prepareStatement(insertQuery); |
| 37 | + pstmt.setString(1, user.getEmail()); |
| 38 | + pstmt.setString(2, user.getName()); |
| 39 | + |
| 40 | + pstmt.executeUpdate(); |
| 41 | + } catch (SQLException exc) { |
| 42 | + logger.error(exc.getMessage()); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + public List<User> findAll() { |
| 47 | + List<User> users = new ArrayList<>(); |
| 48 | + |
| 49 | + try (Connection con = ConnectionUtil.getConnection()) { |
| 50 | + String query = "SELECT * FROM users"; |
| 51 | + PreparedStatement pstmt = con.prepareStatement(query); |
| 52 | + |
| 53 | + ResultSet rs = pstmt.executeQuery(); |
| 54 | + while (rs.next()) { |
| 55 | + User user = new User(); |
| 56 | + user.setEmail(rs.getString("email")); |
| 57 | + user.setName(rs.getString("name")); |
| 58 | + users.add(user); |
| 59 | + } |
| 60 | + } catch (SQLException exc) { |
| 61 | + logger.error(exc.getMessage()); |
| 62 | + } |
| 63 | + |
| 64 | + return users; |
| 65 | + } |
| 66 | + |
| 67 | +} |
0 commit comments