forked from ahmetoguzazik2005/No-Limit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyJDBC.java
More file actions
83 lines (65 loc) · 2.82 KB
/
Copy pathMyJDBC.java
File metadata and controls
83 lines (65 loc) · 2.82 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
import java.sql.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class MyJDBC{
private static final DateTimeFormatter SQL_FORMAT =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
Connection connection;
Statement statement;
ResultSet resultSet;
MyJDBC()throws SQLException{
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/myDB", "root", "password");
statement = connection.createStatement();
}
void createTable() throws SQLException{
if (isThereTable()){
return;
}
String sql =
"CREATE TABLE IF NOT EXISTS StudyBlocks (" +
" start_time DATETIME NOT NULL," +
" finish_time DATETIME NOT NULL" +
")";
statement.executeUpdate(sql); // will be 0 for DDL like CREATE TABLE
}
boolean isThereTable() throws SQLException{
DatabaseMetaData meta = connection.getMetaData();
try (ResultSet rs = meta.getTables(null, null, "studyBlocks", null)) {
if (rs.next()) { // There is already a table
return true;
} else {
return false; // no table yet
}
}
}
public void addStudyBlock(LocalDateTime start, LocalDateTime end) throws SQLException {
Timestamp startTs = Timestamp.valueOf(start);
Timestamp endTs = Timestamp.valueOf(end);
String sql = "INSERT INTO StudyBlocks (start_time, finish_time) VALUES ('"
+ startTs + "', '" + endTs + "')";
statement.executeUpdate(sql);
}
public void makeAListOfADaysStudyBlocks(LocalDate whichDay) throws SQLException {
// start of the day
LocalDateTime startOfDay = whichDay.atStartOfDay(); // yyyy-MM-dd 00:00:00
// start of the next day
LocalDateTime endOfDay = whichDay.plusDays(1).atStartOfDay(); // yyyy-MM-dd+1 00:00:00
// Build SQL string
String query = "SELECT * FROM StudyBlocks " +
"WHERE start_time >= '" + startOfDay.format(SQL_FORMAT) + "' " +
"AND start_time < '" + endOfDay.format(SQL_FORMAT) + "'";
// Execute
try (Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query)) {
while (resultSet.next()) {
// read columns
java.sql.Timestamp startTs = resultSet.getTimestamp("start_time");
java.sql.Timestamp endTs = resultSet.getTimestamp("finish_time");
// Convert to LocalDateTime
LocalDateTime start = startTs.toLocalDateTime();
LocalDateTime end = endTs.toLocalDateTime();
}
}
}
}