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
- Add new database field for Date of Birth
- Add a new GUI field for Date of Birth
- Add GUI code to read Date of Birth
- 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.
Hi, I am new to this.. I am having same problems as jason had… I am currently at adding employee data to table which is 12.6 video tutorial and i want to add date. This source code provided is too hard to understand :/ so I am trying to add manually from descriptions here, but it doesnt work. Shouldnt this part:
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;
go to addEmployeeDialog.java?
Hi Rich,
Yes, thanks for catching this. That code snippet should be in the EmployeeDialog.java. I updated the post. The source code zip file is already correct. Just a copy/paste error in the blog post.
mainly im getting errors whenever dobFormattedTextField = new JFormattedTextField(maskFormatter); is used error says it cant be resolved
or maybe im missing something but as mentioned i am trying to add this code to 12.6 tutorials code
reduced errors 😀 but addemployeeDialog. java is still unresolved would it be possible for you to paste that code?
Hi Richy,
Now I understand the disconnect. The code examples I was referring to is 12.11 and based on all of the new features we added to the app. We even renamed the AddEmployeeDialog to EmployeeDialog since now use it for Add and Update. However, you are using 12.6 which is quite different since we added new features. So that explains the disconnect and the additional code.
In order to help you out, I modified the code for 12.6 “Add Employee” to use the new DOB field. Each area in the code where I made the update, I placed a comment “DOB support”. So you can search the files and find all references for “DOB support”.
However, you should be able to just download the code and test it as is. Here’s the link for this special version of the code.
http://goo.gl/ZhyPDG
Let me know if this helps.
thanks very much, for DOB works great, i came across other problem once i added delete and update buttons, delete works fine, but on update whenever i try to update any thing i come up with erorr saying: Error saving employee: you have an error in your SQL syntax: check mysql server version for right syntax to use near ‘where id=7′ at line 1.
I know that version is same as yours. And im using this:
CREATE TABLE `employees` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`last_name` varchar(64) DEFAULT NULL,
`first_name` varchar(64) DEFAULT NULL,
`job_title` varchar(64) DEFAULT NULL,
`qualification` varchar(64) DEFAULT NULL,
`date_of_birth` DATE DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
INSERT INTO `employees` (`id`,`last_name`,`first_name`,`job_title`, `date_of_birth`, `qualification`) VALUES (2,’Public’,’Mary’,’Prog’, ‘1990-07-11’, ‘Bcs’);
In Java at the moment im not using anything with date_of_birth, it is just in the table. Can date of birth cause any problems even tho i dont mention it anywhere in java?
Hi Richy,
I cover how to handle Employee update in this tutorial.
12.7: Updating an Employee
https://luv2code.com/2014/10/01/java-jdbc-tutorial-part-12-7-connect-java-swing-gui-to-a-mysql-database/
Download and test the working application. Then compare the code to what you have.
Let me know if you need anything else. Cheers!
interesting enough code is the same, the problem is with mysqli think … at the moment i made it as simple as it can be java code is identical except instead of email i renamed everything to job_title.. no syntax error in java, delete, add works fine… but when im trying to update i get ” unknown column ”jobTitle” in field list
Hi Richy,
You are really close 🙂 In your Java code for the EmployeeDAO.update method. The prepared statement SQL string should use “job_title” instead of “jobTitle”.
That should fix it for you. Let me know 🙂
OH MY GOD…. i spent like 4 hours trying to find whats wrong with it.. Thank you very much good Sir!
That is awesome! Glad it worked out 🙂