|
| 1 | +package ru.javawebinar.basejava.storage; |
| 2 | + |
| 3 | +import ru.javawebinar.basejava.exception.NotExistStorageException; |
| 4 | +import ru.javawebinar.basejava.exception.StorageException; |
| 5 | +import ru.javawebinar.basejava.model.Resume; |
| 6 | +import ru.javawebinar.basejava.sql.ConnectionFactory; |
| 7 | + |
| 8 | +import java.sql.*; |
| 9 | +import java.util.List; |
| 10 | + |
| 11 | +public class SqlStorage implements Storage { |
| 12 | + public final ConnectionFactory connectionFactory; |
| 13 | + |
| 14 | + public SqlStorage(String dbUrl, String dbUser, String dbPassword) { |
| 15 | + connectionFactory = () -> DriverManager.getConnection(dbUrl, dbUser, dbPassword); |
| 16 | + } |
| 17 | + |
| 18 | + @Override |
| 19 | + public void clear() { |
| 20 | + try (Connection conn = connectionFactory.getConnection(); |
| 21 | + PreparedStatement ps = conn.prepareStatement("DELETE FROM resume")) { |
| 22 | + ps.execute(); |
| 23 | + } catch (SQLException e) { |
| 24 | + throw new StorageException(e); |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + @Override |
| 29 | + public Resume get(String uuid) { |
| 30 | + try (Connection conn = connectionFactory.getConnection(); |
| 31 | + PreparedStatement ps = conn.prepareStatement("SELECT * FROM resume r WHERE r.uuid =?")) { |
| 32 | + ps.setString(1, uuid); |
| 33 | + ResultSet rs = ps.executeQuery(); |
| 34 | + if (!rs.next()) { |
| 35 | + throw new NotExistStorageException(uuid); |
| 36 | + } |
| 37 | + return new Resume(uuid, rs.getString("full_name")); |
| 38 | + } catch (SQLException e) { |
| 39 | + throw new StorageException(e); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + @Override |
| 44 | + public void update(Resume r) { |
| 45 | + |
| 46 | + } |
| 47 | + |
| 48 | + @Override |
| 49 | + public void save(Resume r) { |
| 50 | + try (Connection conn = connectionFactory.getConnection(); |
| 51 | + PreparedStatement ps = conn.prepareStatement("INSERT INTO resume (uuid, full_name) VALUES (?,?)")) { |
| 52 | + ps.setString(1, r.getUuid()); |
| 53 | + ps.setString(2, r.getFullName()); |
| 54 | + ps.execute(); |
| 55 | + } catch (SQLException e) { |
| 56 | + throw new StorageException(e); |
| 57 | + } |
| 58 | + |
| 59 | + } |
| 60 | + |
| 61 | + @Override |
| 62 | + public void delete(String uuid) { |
| 63 | + |
| 64 | + } |
| 65 | + |
| 66 | + @Override |
| 67 | + public List<Resume> getAllSorted() { |
| 68 | + return null; |
| 69 | + } |
| 70 | + |
| 71 | + @Override |
| 72 | + public int size() { |
| 73 | + return 0; |
| 74 | + } |
| 75 | +} |
0 commit comments