-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPostgresExample.java
More file actions
112 lines (91 loc) · 4.45 KB
/
PostgresExample.java
File metadata and controls
112 lines (91 loc) · 4.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package org.example;
import org.example.model.Cat;
import org.example.model.CatBehaviour;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import static org.example.model.CatBehaviour.CALM;
import static org.example.model.CatBehaviour.CRAZY;
public class PostgresExample {
public static void main(String[] args) {
//Створюємо підключення до БД
String url = "jdbc:postgresql://localhost:5432/db_cats";
Connection conn;
try {
conn = DriverManager.getConnection(url, "postgres_user", "postgres_password");
} catch (SQLException e) {
throw new RuntimeException("Cannot connect to DB", e);
}
//Створюємо таблицю, в якій зберігатимемо інформацію про котів
String createTableSql = "CREATE TABLE IF NOT EXISTS cats (cat_name TEXT PRIMARY KEY, behaviour TEXT)";
try (PreparedStatement createTableStmt = conn.prepareStatement(createTableSql)) {
createTableStmt.execute();
} catch (SQLException e) {
throw new RuntimeException("Cannot connect to DB", e);
}
Cat cat1 = new Cat("Tom", CALM);
Cat cat2 = new Cat("Murzyk", CRAZY);
//Створюємо 2х котів в одній транзакції
String insertSql = "INSERT INTO cats (cat_name, behaviour) VALUES (?, ?)";
try (PreparedStatement insertStmt = conn.prepareStatement(insertSql)) {
//Починаємо транзакцію
conn.setAutoCommit(false);
insertStmt.setString(1, cat1.getName());
insertStmt.setString(2, cat1.getBehaviour().toString());
insertStmt.executeUpdate();
insertStmt.setString(1, cat2.getName());
insertStmt.setString(2, cat2.getBehaviour().toString());
insertStmt.executeUpdate();
//Зберігаємо всі зміни, які зробили в транзакції в БД
conn.commit();
conn.setAutoCommit(true);
} catch (SQLException e) {
throw new RuntimeException("Cannot connect to DB", e);
}
//Дістаємо котів з БД
String selectSql = "SELECT * FROM cats";
try (PreparedStatement insertStmt = conn.prepareStatement(selectSql);
ResultSet resultSet = insertStmt.executeQuery()) {
List<Cat> cats = new ArrayList<>();
while (resultSet.next()) {
String catName = resultSet.getString("cat_name");
CatBehaviour behaviour = CatBehaviour.valueOf(resultSet.getString("behaviour"));
cats.add(new Cat(catName, behaviour));
}
System.out.println("Коти збережені в базі даних:");
System.out.println(cats);
} catch (SQLException e) {
throw new RuntimeException("Cannot connect to DB", e);
}
//Видаляємо котів з бази даних
String deleteSql = "DELETE FROM cats WHERE cat_name = ?";
try (PreparedStatement deleteStmt = conn.prepareStatement(deleteSql)) {
deleteStmt.setString(1, cat1.getName());
deleteStmt.executeUpdate();
deleteStmt.setString(1, cat2.getName());
deleteStmt.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException("Cannot connect to DB", e);
}
//Дістаємо котів з БД
try (PreparedStatement insertStmt = conn.prepareStatement(selectSql);
ResultSet resultSet = insertStmt.executeQuery()) {
List<Cat> cats = new ArrayList<>();
while (resultSet.next()) {
String catName = resultSet.getString("cat_name");
CatBehaviour behaviour = CatBehaviour.valueOf(resultSet.getString("behaviour"));
cats.add(new Cat(catName, behaviour));
}
System.out.println("Коти збережені в базі даних після видалення доданих котів:");
System.out.println(cats);
} catch (SQLException e) {
throw new RuntimeException("Cannot connect to DB", e);
}
// Закриваємо підключення до БД
try {
conn.close();
} catch (SQLException e) {
throw new RuntimeException("Cannot connect to DB", e);
}
}
}