1
+ /**
2
+ * EmployeeDatabase_Q26.java
3
+ *
4
+ * This program demonstrates JDBC connectivity with a database to store and retrieve
5
+ * employee records. It includes a GUI for data entry and display.
6
+ *
7
+ * Note: This program requires the appropriate JDBC driver for MySQL or PostgreSQL
8
+ * to be in the classpath.
9
+ */
10
+
11
+ import javax .swing .*;
12
+ import java .awt .*;
13
+ import java .awt .event .*;
14
+ import java .sql .*;
15
+ import javax .swing .table .DefaultTableModel ;
16
+
17
+ public class EmployeeDatabase_Q26 extends JFrame {
18
+ // JDBC Database URL, Username, and Password
19
+ // Change these values according to your database setup
20
+ private static final String DB_URL = "jdbc:mysql://localhost:3306/employee_db" ;
21
+ private static final String DB_USER = "root" ;
22
+ private static final String DB_PASSWORD = "password" ;
23
+
24
+ // UI Components
25
+ private JTextField nameField ;
26
+ private JTextField codeField ;
27
+ private JTextField designationField ;
28
+ private JTextField salaryField ;
29
+ private JButton saveButton ;
30
+ private JButton viewButton ;
31
+ private JButton clearButton ;
32
+ private JTable employeeTable ;
33
+ private DefaultTableModel tableModel ;
34
+
35
+ public EmployeeDatabase_Q26 () {
36
+ // Set up the frame
37
+ super ("Employee Database" );
38
+ setDefaultCloseOperation (JFrame .EXIT_ON_CLOSE );
39
+ setSize (600 , 500 );
40
+ setLocationRelativeTo (null );
41
+
42
+ // Create the main panel with a border layout
43
+ JPanel mainPanel = new JPanel (new BorderLayout (10 , 10 ));
44
+ mainPanel .setBorder (BorderFactory .createEmptyBorder (10 , 10 , 10 , 10 ));
45
+
46
+ // Create the input form panel
47
+ JPanel formPanel = createFormPanel ();
48
+ mainPanel .add (formPanel , BorderLayout .NORTH );
49
+
50
+ // Create the table panel
51
+ JPanel tablePanel = createTablePanel ();
52
+ mainPanel .add (tablePanel , BorderLayout .CENTER );
53
+
54
+ // Set the content pane
55
+ setContentPane (mainPanel );
56
+
57
+ // Initialize the database
58
+ initializeDatabase ();
59
+ }
60
+
61
+ private JPanel createFormPanel () {
62
+ JPanel panel = new JPanel (new GridBagLayout ());
63
+ panel .setBorder (BorderFactory .createTitledBorder ("Employee Information" ));
64
+
65
+ GridBagConstraints gbc = new GridBagConstraints ();
66
+ gbc .fill = GridBagConstraints .HORIZONTAL ;
67
+ gbc .insets = new Insets (5 , 5 , 5 , 5 );
68
+
69
+ // Name field
70
+ gbc .gridx = 0 ;
71
+ gbc .gridy = 0 ;
72
+ panel .add (new JLabel ("Name:" ), gbc );
73
+
74
+ gbc .gridx = 1 ;
75
+ gbc .gridy = 0 ;
76
+ gbc .weightx = 1.0 ;
77
+ nameField = new JTextField (20 );
78
+ panel .add (nameField , gbc );
79
+
80
+ // Code field
81
+ gbc .gridx = 0 ;
82
+ gbc .gridy = 1 ;
83
+ gbc .weightx = 0.0 ;
84
+ panel .add (new JLabel ("Code:" ), gbc );
85
+
86
+ gbc .gridx = 1 ;
87
+ gbc .gridy = 1 ;
88
+ gbc .weightx = 1.0 ;
89
+ codeField = new JTextField (10 );
90
+ panel .add (codeField , gbc );
91
+
92
+ // Designation field
93
+ gbc .gridx = 0 ;
94
+ gbc .gridy = 2 ;
95
+ gbc .weightx = 0.0 ;
96
+ panel .add (new JLabel ("Designation:" ), gbc );
97
+
98
+ gbc .gridx = 1 ;
99
+ gbc .gridy = 2 ;
100
+ gbc .weightx = 1.0 ;
101
+ designationField = new JTextField (20 );
102
+ panel .add (designationField , gbc );
103
+
104
+ // Salary field
105
+ gbc .gridx = 0 ;
106
+ gbc .gridy = 3 ;
107
+ gbc .weightx = 0.0 ;
108
+ panel .add (new JLabel ("Salary:" ), gbc );
109
+
110
+ gbc .gridx = 1 ;
111
+ gbc .gridy = 3 ;
112
+ gbc .weightx = 1.0 ;
113
+ salaryField = new JTextField (10 );
114
+ panel .add (salaryField , gbc );
115
+
116
+ // Button panel
117
+ JPanel buttonPanel = new JPanel (new FlowLayout (FlowLayout .CENTER , 10 , 0 ));
118
+
119
+ saveButton = new JButton ("Save" );
120
+ saveButton .addActionListener (e -> saveEmployee ());
121
+
122
+ viewButton = new JButton ("View All" );
123
+ viewButton .addActionListener (e -> viewAllEmployees ());
124
+
125
+ clearButton = new JButton ("Clear" );
126
+ clearButton .addActionListener (e -> clearForm ());
127
+
128
+ buttonPanel .add (saveButton );
129
+ buttonPanel .add (viewButton );
130
+ buttonPanel .add (clearButton );
131
+
132
+ gbc .gridx = 0 ;
133
+ gbc .gridy = 4 ;
134
+ gbc .gridwidth = 2 ;
135
+ gbc .weightx = 1.0 ;
136
+ panel .add (buttonPanel , gbc );
137
+
138
+ return panel ;
139
+ }
140
+
141
+ private JPanel createTablePanel () {
142
+ JPanel panel = new JPanel (new BorderLayout ());
143
+ panel .setBorder (BorderFactory .createTitledBorder ("Employee Records" ));
144
+
145
+ // Create the table model with column names
146
+ String [] columnNames = {"Name" , "Code" , "Designation" , "Salary" };
147
+ tableModel = new DefaultTableModel (columnNames , 0 );
148
+
149
+ // Create the table and add it to a scroll pane
150
+ employeeTable = new JTable (tableModel );
151
+ JScrollPane scrollPane = new JScrollPane (employeeTable );
152
+
153
+ panel .add (scrollPane , BorderLayout .CENTER );
154
+
155
+ return panel ;
156
+ }
157
+
158
+ private void initializeDatabase () {
159
+ try (Connection conn = getConnection ()) {
160
+ // Create the employee table if it doesn't exist
161
+ String createTableSQL =
162
+ "CREATE TABLE IF NOT EXISTS employees (" +
163
+ "id INT AUTO_INCREMENT PRIMARY KEY," +
164
+ "name VARCHAR(100) NOT NULL," +
165
+ "code VARCHAR(20) NOT NULL," +
166
+ "designation VARCHAR(100) NOT NULL," +
167
+ "salary DECIMAL(10, 2) NOT NULL)" ;
168
+
169
+ try (Statement stmt = conn .createStatement ()) {
170
+ stmt .execute (createTableSQL );
171
+ System .out .println ("Database initialized successfully." );
172
+ }
173
+ } catch (SQLException e ) {
174
+ showError ("Database Initialization Error" , e .getMessage ());
175
+ e .printStackTrace ();
176
+ }
177
+ }
178
+
179
+ private void saveEmployee () {
180
+ // Get the input values
181
+ String name = nameField .getText ().trim ();
182
+ String code = codeField .getText ().trim ();
183
+ String designation = designationField .getText ().trim ();
184
+ String salaryStr = salaryField .getText ().trim ();
185
+
186
+ // Validate the input
187
+ if (name .isEmpty () || code .isEmpty () || designation .isEmpty () || salaryStr .isEmpty ()) {
188
+ showError ("Input Error" , "All fields are required." );
189
+ return ;
190
+ }
191
+
192
+ double salary ;
193
+ try {
194
+ salary = Double .parseDouble (salaryStr );
195
+ } catch (NumberFormatException e ) {
196
+ showError ("Input Error" , "Salary must be a valid number." );
197
+ return ;
198
+ }
199
+
200
+ // Insert the employee record into the database
201
+ try (Connection conn = getConnection ()) {
202
+ String insertSQL =
203
+ "INSERT INTO employees (name, code, designation, salary) " +
204
+ "VALUES (?, ?, ?, ?)" ;
205
+
206
+ try (PreparedStatement pstmt = conn .prepareStatement (insertSQL )) {
207
+ pstmt .setString (1 , name );
208
+ pstmt .setString (2 , code );
209
+ pstmt .setString (3 , designation );
210
+ pstmt .setDouble (4 , salary );
211
+
212
+ int rowsAffected = pstmt .executeUpdate ();
213
+ if (rowsAffected > 0 ) {
214
+ JOptionPane .showMessageDialog (this ,
215
+ "Employee record saved successfully." ,
216
+ "Success" , JOptionPane .INFORMATION_MESSAGE );
217
+
218
+ // Clear the form and refresh the table
219
+ clearForm ();
220
+ viewAllEmployees ();
221
+ }
222
+ }
223
+ } catch (SQLException e ) {
224
+ showError ("Database Error" , e .getMessage ());
225
+ e .printStackTrace ();
226
+ }
227
+ }
228
+
229
+ private void viewAllEmployees () {
230
+ // Clear the existing table data
231
+ tableModel .setRowCount (0 );
232
+
233
+ // Retrieve all employee records from the database
234
+ try (Connection conn = getConnection ()) {
235
+ String selectSQL = "SELECT name, code, designation, salary FROM employees" ;
236
+
237
+ try (Statement stmt = conn .createStatement ();
238
+ ResultSet rs = stmt .executeQuery (selectSQL )) {
239
+
240
+ // Add each employee record to the table model
241
+ while (rs .next ()) {
242
+ String name = rs .getString ("name" );
243
+ String code = rs .getString ("code" );
244
+ String designation = rs .getString ("designation" );
245
+ double salary = rs .getDouble ("salary" );
246
+
247
+ Object [] row = {name , code , designation , salary };
248
+ tableModel .addRow (row );
249
+ }
250
+
251
+ if (tableModel .getRowCount () == 0 ) {
252
+ JOptionPane .showMessageDialog (this ,
253
+ "No employee records found." ,
254
+ "Information" , JOptionPane .INFORMATION_MESSAGE );
255
+ }
256
+ }
257
+ } catch (SQLException e ) {
258
+ showError ("Database Error" , e .getMessage ());
259
+ e .printStackTrace ();
260
+ }
261
+ }
262
+
263
+ private void clearForm () {
264
+ nameField .setText ("" );
265
+ codeField .setText ("" );
266
+ designationField .setText ("" );
267
+ salaryField .setText ("" );
268
+ nameField .requestFocus ();
269
+ }
270
+
271
+ private void showError (String title , String message ) {
272
+ JOptionPane .showMessageDialog (this , message , title , JOptionPane .ERROR_MESSAGE );
273
+ }
274
+
275
+ private Connection getConnection () throws SQLException {
276
+ return DriverManager .getConnection (DB_URL , DB_USER , DB_PASSWORD );
277
+ }
278
+
279
+ public static void main (String [] args ) {
280
+ // Load the JDBC driver
281
+ try {
282
+ // For MySQL
283
+ Class .forName ("com.mysql.cj.jdbc.Driver" );
284
+
285
+ // For PostgreSQL
286
+ // Class.forName("org.postgresql.Driver");
287
+
288
+ // Create and display the GUI on the Event Dispatch Thread
289
+ SwingUtilities .invokeLater (() -> {
290
+ new EmployeeDatabase_Q26 ().setVisible (true );
291
+ });
292
+ } catch (ClassNotFoundException e ) {
293
+ JOptionPane .showMessageDialog (null ,
294
+ "JDBC Driver not found. Please add the appropriate JDBC driver to the classpath." ,
295
+ "Driver Error" , JOptionPane .ERROR_MESSAGE );
296
+ e .printStackTrace ();
297
+ }
298
+ }
299
+ }
0 commit comments