-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseHandler.java
More file actions
60 lines (54 loc) · 2.25 KB
/
Copy pathDatabaseHandler.java
File metadata and controls
60 lines (54 loc) · 2.25 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
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHandler {
private Connection connection;
private static final String URL = "jdbc:mysql://127.0.0.1:3307/athul";
private static final String USERNAME = "root";
private static final String PASSWORD = "";
private static DatabaseHandler instance;
private DatabaseHandler() {
try {
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
}
}
public static synchronized DatabaseHandler getInstance() {
if (instance == null) {
instance = new DatabaseHandler();
}
return instance;
}
public void saveMessage(String sender, String recipient, String message) {
String query = "INSERT INTO communication (senderName, recipientName, message) VALUES (?, ?, ?)";
try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
preparedStatement.setString(1, sender);
preparedStatement.setString(2, recipient);
preparedStatement.setString(3, message);
preparedStatement.executeUpdate();
//System.out.println("hello wrol");
} catch (SQLException e) {
System.out.println("int the insert command");
e.printStackTrace();
}
}
public List<String> getChatHistory(String sender, String recipient) {
List<String> history = new ArrayList<>();
String query = "SELECT * FROM communication WHERE senderName = ? AND recipientName = ?";
try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
preparedStatement.setString(1, sender);
preparedStatement.setString(2, recipient);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
String time = resultSet.getString("time");
String message = resultSet.getString("message");
history.add(time + " - " + message);
}
} catch (SQLException e) {
System.out.println("int the databasehandler");
e.printStackTrace();
}
return history;
}
}