-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpratical1.java
More file actions
366 lines (316 loc) · 13.1 KB
/
pratical1.java
File metadata and controls
366 lines (316 loc) · 13.1 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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.table.DefaultTableModel;
public class pratical1 extends JFrame {
private static final String DB_URL = "jdbc:mysql://localhost:3306/startersql?useSSL=false&serverTimezone=UTC";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "yourpass";
// UI components
private final JTextField tfId = new JTextField(10);
private final JTextField tfName = new JTextField(20);
private final JTextField tfEmail = new JTextField(20);
private final JTextField tfGender = new JTextField(10);
private final JTextField tfDob = new JTextField(10);
private final JTextField tfCreatedAt = new JTextField(20);
private final JButton btnInsert = new JButton("Insert");
private final JButton btnUpdate = new JButton("Update");
private final JButton btnDelete = new JButton("Delete");
private final JButton btnRefresh = new JButton("Refresh");
private final JButton btnFirst = new JButton("|< First");
private final JButton btnPrev = new JButton("< Prev");
private final JButton btnNext = new JButton("Next >");
private final JButton btnLast = new JButton("Last >|");
private final DefaultTableModel model = new DefaultTableModel(
new Object[]{"ID", "Name", "Email", "Gender", "Date of Birth", "Created At"}, 0
) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
private final JTable table = new JTable(model);
// JDBC objects
private Connection conn;
private Statement navStmt;
private ResultSet navRs;
public pratical1() {
super("Practical 1 — Swing + JDBC CRUD (startersql.users)");
buildUI();
connect();
refreshAll();
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
cleanup();
System.exit(0);
}
});
setSize(900, 560);
setLocationRelativeTo(null);
setVisible(true);
}
private void buildUI() {
// form panel
JPanel form = new JPanel(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.insets = new Insets(4, 6, 4, 6);
gc.fill = GridBagConstraints.HORIZONTAL;
tfId.setEditable(false);
tfCreatedAt.setEditable(false);
int r = 0;
gc.gridx = 0; gc.gridy = r; form.add(new JLabel("ID:"), gc);
gc.gridx = 1; form.add(tfId, gc);
gc.gridx = 2; form.add(new JLabel("Name:"), gc);
gc.gridx = 3; form.add(tfName, gc);
r++;
gc.gridx = 0; gc.gridy = r; form.add(new JLabel("Email:"), gc);
gc.gridx = 1; form.add(tfEmail, gc);
gc.gridx = 2; form.add(new JLabel("Gender:"), gc);
gc.gridx = 3; form.add(tfGender, gc);
r++;
gc.gridx = 0; gc.gridy = r; form.add(new JLabel("Date of Birth (yyyy-MM-dd):"), gc);
gc.gridx = 1; form.add(tfDob, gc);
gc.gridx = 2; form.add(new JLabel("Created At:"), gc);
gc.gridx = 3; form.add(tfCreatedAt, gc);
// buttons row
JPanel bp = new JPanel(new FlowLayout(FlowLayout.LEFT, 6, 0));
bp.add(btnInsert);
bp.add(btnUpdate);
bp.add(btnDelete);
bp.add(btnRefresh);
bp.add(new JSeparator(SwingConstants.VERTICAL));
bp.add(btnFirst);
bp.add(btnPrev);
bp.add(btnNext);
bp.add(btnLast);
// table
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll = new JScrollPane(table);
// layout
JPanel top = new JPanel(new BorderLayout());
top.add(form, BorderLayout.CENTER);
top.add(bp, BorderLayout.SOUTH);
setLayout(new BorderLayout(6, 6));
add(top, BorderLayout.NORTH);
add(scroll, BorderLayout.CENTER);
// event handlers
btnInsert.addActionListener(e -> insertRecord());
btnUpdate.addActionListener(e -> updateRecord());
btnDelete.addActionListener(e -> deleteRecord());
btnRefresh.addActionListener(e -> refreshAll());
btnFirst.addActionListener(e -> navigate("FIRST"));
btnPrev.addActionListener(e -> navigate("PREV"));
btnNext.addActionListener(e -> navigate("NEXT"));
btnLast.addActionListener(e -> navigate("LAST"));
table.getSelectionModel().addListSelectionListener((ListSelectionEvent e) -> {
if (!e.getValueIsAdjusting()) {
int row = table.getSelectedRow();
if (row >= 0) {
tfId.setText(String.valueOf(model.getValueAt(row, 0)));
tfName.setText(String.valueOf(model.getValueAt(row, 1)));
tfEmail.setText(String.valueOf(model.getValueAt(row, 2)));
tfGender.setText(String.valueOf(model.getValueAt(row, 3)));
tfDob.setText(String.valueOf(model.getValueAt(row, 4)));
tfCreatedAt.setText(String.valueOf(model.getValueAt(row, 5)));
}
}
});
}
private void connect() {
try {
Class.forName("com.mysql.cj.jdbc.Driver"); // optional for modern drivers
conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
} catch (Exception ex) {
showError("Failed to connect to DB", ex);
}
}
private void refreshAll() {
loadTable();
openScrollableResultSet();
}
private void loadTable() {
model.setRowCount(0);
String sql = "SELECT id, name, email, gender, date_of_birth, created_at FROM users ORDER BY id";
try (PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
Vector<Object> row = new Vector<>();
row.add(rs.getInt("id"));
row.add(rs.getString("name"));
row.add(rs.getString("email"));
row.add(rs.getString("gender"));
row.add(rs.getDate("date_of_birth"));
row.add(rs.getTimestamp("created_at"));
model.addRow(row);
}
if (model.getRowCount() > 0) {
table.setRowSelectionInterval(0, 0);
} else {
clearForm();
}
} catch (SQLException ex) {
showError("Failed to load table", ex);
}
}
private void openScrollableResultSet() {
// close previous
closeNav();
String sql = "SELECT id, name, email, gender, date_of_birth, created_at FROM users ORDER BY id";
try {
navStmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
navRs = navStmt.executeQuery(sql);
if (navRs.next()) {
showCurrentFromNav();
}
} catch (SQLException ex) {
showError("Failed to open navigation ResultSet", ex);
}
}
private void showCurrentFromNav() throws SQLException {
if (navRs == null) return;
int id = navRs.getInt("id");
String name = navRs.getString("name");
String email = navRs.getString("email");
String gender = navRs.getString("gender");
Date dob = navRs.getDate("date_of_birth");
Timestamp created = navRs.getTimestamp("created_at");
tfId.setText(String.valueOf(id));
tfName.setText(name);
tfEmail.setText(email);
tfGender.setText(gender);
tfDob.setText(dob != null ? dob.toString() : "");
tfCreatedAt.setText(created != null ? created.toString() : "");
// also select in JTable
int targetRow = -1;
for (int r = 0; r < model.getRowCount(); r++) {
Object v = model.getValueAt(r, 0);
if (v != null && Integer.parseInt(v.toString()) == id) {
targetRow = r;
break;
}
}
if (targetRow >= 0) {
table.setRowSelectionInterval(targetRow, targetRow);
table.scrollRectToVisible(table.getCellRect(targetRow, 0, true));
}
}
private void navigate(String where) {
try {
if (navRs == null) return;
boolean moved = false;
switch (where) {
case "FIRST": moved = navRs.first(); break;
case "PREV": moved = navRs.previous(); if (!moved) moved = navRs.first(); break;
case "NEXT": moved = navRs.next(); if (!moved) moved = navRs.last(); break;
case "LAST": moved = navRs.last(); break;
}
if (moved) showCurrentFromNav();
} catch (SQLException ex) {
showError("Navigation error", ex);
}
}
private void insertRecord() {
String name = tfName.getText().trim();
String email = tfEmail.getText().trim();
String gender = tfGender.getText().trim();
String dobStr = tfDob.getText().trim();
if (name.isEmpty() || email.isEmpty() || dobStr.isEmpty()) {
JOptionPane.showMessageDialog(this, "Name, Email and Date of Birth are required.");
return;
}
String sql = "INSERT INTO users (name, email, gender, date_of_birth) VALUES (?, ?, ?, ?)";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, gender);
ps.setDate(4, java.sql.Date.valueOf(dobStr)); // requires yyyy-MM-dd
ps.executeUpdate();
refreshAll();
JOptionPane.showMessageDialog(this, "Inserted successfully.");
} catch (SQLException ex) {
showError("Insert failed", ex);
} catch (IllegalArgumentException ie) {
JOptionPane.showMessageDialog(this, "Date must be in yyyy-MM-dd format.");
}
}
private void updateRecord() {
String idStr = tfId.getText().trim();
if (idStr.isEmpty()) {
JOptionPane.showMessageDialog(this, "Select a record first.");
return;
}
String name = tfName.getText().trim();
String email = tfEmail.getText().trim();
String gender = tfGender.getText().trim();
String dobStr = tfDob.getText().trim();
String sql = "UPDATE users SET name=?, email=?, gender=?, date_of_birth=? WHERE id=?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, gender);
ps.setDate(4, java.sql.Date.valueOf(dobStr));
ps.setInt(5, Integer.parseInt(idStr));
int updated = ps.executeUpdate();
if (updated > 0) {
refreshAll();
JOptionPane.showMessageDialog(this, "Updated successfully.");
} else {
JOptionPane.showMessageDialog(this, "No record updated (ID not found).");
}
} catch (SQLException ex) {
showError("Update failed", ex);
} catch (IllegalArgumentException ie) {
JOptionPane.showMessageDialog(this, "Date must be in yyyy-MM-dd format.");
}
}
private void deleteRecord() {
String idStr = tfId.getText().trim();
if (idStr.isEmpty()) {
JOptionPane.showMessageDialog(this, "Select a record first.");
return;
}
int confirm = JOptionPane.showConfirmDialog(this, "Delete record ID " + idStr + "?", "Confirm Delete", JOptionPane.YES_NO_OPTION);
if (confirm != JOptionPane.YES_OPTION) return;
String sql = "DELETE FROM users WHERE id=?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, Integer.parseInt(idStr));
int deleted = ps.executeUpdate();
if (deleted > 0) {
refreshAll();
JOptionPane.showMessageDialog(this, "Deleted successfully.");
} else {
JOptionPane.showMessageDialog(this, "ID not found.");
}
} catch (SQLException ex) {
showError("Delete failed", ex);
}
}
private void clearForm() {
tfId.setText("");
tfName.setText("");
tfEmail.setText("");
tfGender.setText("");
tfDob.setText("");
tfCreatedAt.setText("");
}
private void closeNav() {
try { if (navRs != null) navRs.close(); } catch (Exception ignored) {}
try { if (navStmt != null) navStmt.close(); } catch (Exception ignored) {}
navRs = null; navStmt = null;
}
private void cleanup() {
closeNav();
try { if (conn != null) conn.close(); } catch (Exception ignored) {}
}
private void showError(String msg, Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, msg + "\n" + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(pratical1::new);
}
}