Lesson13 SqlStorage · JavaWebinar/basejava@62705ea · GitHub
Skip to content

Commit 62705ea

Browse files
author
Tanechka
committed
Lesson13 SqlStorage
1 parent 25f4dd3 commit 62705ea

4 files changed

Lines changed: 90 additions & 4 deletions

File tree

src/ru/javawebinar/basejava/exception/StorageException.java

Lines changed: 4 additions & 0 deletions
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package ru.javawebinar.basejava.sql;
2+
3+
import java.sql.Connection;
4+
import java.sql.SQLException;
5+
6+
public interface ConnectionFactory {
7+
Connection getConnection() throws SQLException;
8+
}
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
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+
}

test/ru/javawebinar/basejava/storage/AbstractStorageTest.java

Lines changed: 3 additions & 4 deletions

0 commit comments

Comments
 (0)