Hi All, Things have being going good with the JDBC Swing GUI video series. I had a YouTube subscriber ask if I could expand on this example and show how to handle dates. So, in this post, we’ll add support for read/write the date of birth for an employee.

Overview of the Steps

  1. Add new database field for Date of Birth
  2. Add a new GUI field for Date of Birth
  3. Add GUI code to read Date of Birth
  4. Add DAO code to read/write Date of Birth

Step 1: Add new a new datebase field for Date of Birth

We need to add a new database field for Date or Birth.

Here’s the updated SQL for the Employee table.

[code]
CREATE TABLE `employees` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`last_name` varchar(64) DEFAULT NULL,
`first_name` varchar(64) DEFAULT NULL,
`email` varchar(64) DEFAULT NULL,
`department` varchar(64) DEFAULT NULL,
`salary` DECIMAL(10,2) DEFAULT NULL,
`date_of_birth` DATE DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
[/code]

Step 2: Add a new GUI field for Date of Birth

We need to add a new  field for the Date of Birth field. This field will make use a formatting to make sure the user can only enter numbers for the date. Also, when they attempt to save, we will validate the date field.

Here’s a screen shot of the GUI. Notice the new Date of Birth field.

To make sure the user only enters numbers for the date, we make use of a mask formatter. Here’s the source code for this section:

File: EmployeeDialog.java

[code]

String maskFormat = "##/##/####";
MaskFormatter maskFormatter = null;

try {
maskFormatter = new MaskFormatter(maskFormat);
} catch (Exception exc) {
exc.printStackTrace();
}

dobFormattedTextField = new JFormattedTextField(maskFormatter);
[/code]

Step 3: Add GUI code to read Date of Birth

When the user enters the date and selects Save, we need to retrieve the date and set it on the employee object. When we read the date, it is initially a String. We need to convert it to a date object. If the String is an invalid date then this will throw an exception. We can inform the user of the invalid date.

File: EmployeeDialog.java

[code]
protected void saveEmployee() {

// get the employee info from gui
String firstName = firstNameTextField.getText();
String lastName = lastNameTextField.getText();
String email = emailTextField.getText();

String salaryStr = salaryTextField.getText();
BigDecimal salary = convertStringToBigDecimal(salaryStr);

Date dateOfBirth = null;

try {
dateOfBirth = getEmployeeDateOfBirth();
} catch (Exception exc) {
JOptionPane.showMessageDialog(this,
"Invalid Date of Birth: " + exc.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
return;
}

}

private Date getEmployeeDateOfBirth() throws Exception {

Date theDate = null;
String stripped = null;

String info = dobFormattedTextField.getText();

// remove the mask characters
if (info != null) {
stripped = info.replaceAll("/", "");
}

// check for valid date
if (stripped != null && stripped.trim().length() > 0) {
theDate = dateFormat.parse(info);
}
else {
theDate = null;
}

return theDate;
}

[/code]

Step 4: Add DAO code to read/write Date of Birth

Finally, in our DAO code, we need to add code to read and write the new date of birth field.

Here’s the snippet for inserting the date into the database.

File: EmployeeDAO.java

[code]
public void addEmployee(Employee theEmployee, int userId) throws Exception {
PreparedStatement myStmt = null;

try {
// prepare statement
myStmt = myConn.prepareStatement("insert into employees"
+ " (first_name, last_name, email, salary, date_of_birth)"
+ " values (?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS);

// set params
myStmt.setString(1, theEmployee.getFirstName());
myStmt.setString(2, theEmployee.getLastName());
myStmt.setString(3, theEmployee.getEmail());
myStmt.setBigDecimal(4, theEmployee.getSalary());

java.sql.Date dateOfBirth = null;
if (theEmployee.getDateOfBirth() != null) {
dateOfBirth = new java.sql.Date(theEmployee.getDateOfBirth().getTime());
}

myStmt.setDate(5, dateOfBirth);

// execute SQL
myStmt.executeUpdate();


}
[/code]

Now, here’s the code for reading the date field.

File: EmployeeDAO.java

[code]
private Employee convertRowToEmployee(ResultSet myRs) throws SQLException {

int id = myRs.getInt("id");
String lastName = myRs.getString("last_name");
String firstName = myRs.getString("first_name");
String email = myRs.getString("email");
BigDecimal salary = myRs.getBigDecimal("salary");
Date dateOfBirth = myRs.getDate("date_of_birth");

Employee tempEmployee = new Employee(id, lastName, firstName, email, salary, dateOfBirth);

return tempEmployee;
}

[/code]

Wrap Up

In this post, I wanted to highlight the major changes. I made additional changes to the app such as adding the date field in the Employee class and updating the code in the EmployeeTableModel. You can download the code and review all of those changes. Just search for “dateOfBirth” in the source files.

Download Java Source Code