Today is Monday, 4th July 2022

Archive for November, 2014

Java JDBC Tutorial – Part 12.x: Creating Runnable JAR file with Eclipse

In this blog post, I’ll show you how to create an runnable JAR file. This will use the code from video 12.10.

A runnable JAR file allows you to have a single JAR file that includes all Java class files and supporting libraries. In our case, this includes the JAR files for the MySQL JDBC driver (client api code only) and the JAR file for the GUI library JGoodies. Once the JAR file is created, then you’ll be able to double-click the JAR file in the file manager and the application will start.

Follow these steps.

  1. Download the source code from video 12.10 from this link
  2. Unzip the zip file to a directory on your computer. I’ll refer to this directory later on as as ${jdbc-demo-code}
  3. In Eclipse, import the code using:
    1. Select File > Import > General > Existing Projects into Workspace
    2. Select root directory: Browse to the directory where you unzipped the code: ${jdbc-demo-code}
    3. Click Finish
  4. Run your project first to make sure it works
    1. Open the file: in the package: com.luv2code.jdbc.employeesearch.ui
    2. Right click in the file and select Run As > Java Application
  5. Create a new folder under your current project
    1. Select the root folder of your project: jdbc-swing-gui-check-password
    2. Right click and select New > Folder
    3. For folder name, enter: target
    4. Click Finish.
  6. Copy the props file to the target folder
    1. Select the file and copy it to the folder: target
    2. Note: Your JAR file will use this properties file
  7. Export to a Runnable JAR file
    1. Select the root folder of your project: jdbc-swing-gui-check-password
    2. Right click and select Export…
    3. Select Java > Runnable JAR file
    4. Click Next
  8. Set the target options
    1. For Launch configuration, choose the one that says: EmployeeSearchApp …
    2. For Export destination, click the Browse… button
    3. Select the target directory you created in a previous step
    4. For the file name Save As, enter: jdbc-demo-app.jar
    5. For Library handling, select: Extract required libraries into generated JAR
    6. Click Finish
    7. Note: the export will finish with warnings. You can safely ignore them.
  9. If everything worked properly then you will have the following directory structure:
    • jdbc-swing-gui-check-password/target
      • jdbc-demo-app.jar
  10. You can run the program using your Windows Explorer or Mac Finder.
    • Move to the directory where your jdbc-demo-app.jar is located
    • Double-click the file and it should run and connect to your database.

* Troubleshooting.

  1. If you have problems then you should run from command-line to see details of the stacktrace.
  2. Open a command-line window and navigate to where the jdbc-demo-app.jar is located
  3. Run from command-line with: java -jar jdbc-demo-app.jar
  4. View the stacktrace and it will tell you what the problem is.

Java JDBC Tutorial – Part 12.11: Connect Java Swing GUI to a MySQL Database – Date of Birth

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.

CREATE TABLE `employees` (
  `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`)

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:


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

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

dobFormattedTextField = new JFormattedTextField(maskFormatter);

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.


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) {
				"Invalid Date of Birth: " + exc.getMessage(), "Error",

	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;

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.


	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

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


	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;

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

Java JDBC Tutorial – Part 12.10: Connect Java Swing GUI to a MySQL Database

In this video we will learn how to connect a Java GUI to a MySQL database. We will add support to check a user’s password during login.

Note: All initial passwords are set to: java <--(all lower-case) Please SUBSCRIBE to my YouTube channel.

Download Java Source Code