Today is Saturday, 11th February 2017

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: EmployeeeSearchApp.java 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 demo.properties 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
      • demo.properties
  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.
Share


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 <code>employees</code> (
<code>id</code> int(11) NOT NULL AUTO_INCREMENT,
<code>last_name</code> varchar(64) DEFAULT NULL,
<code>first_name</code> varchar(64) DEFAULT NULL,
<code>email</code> varchar(64) DEFAULT NULL,
<code>department</code> varchar(64) DEFAULT NULL,
<code>salary</code> DECIMAL(10,2) DEFAULT NULL,
<code>date_of_birth</code> DATE DEFAULT NULL,
PRIMARY KEY (<code>id</code>)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

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

String maskFormat = "##/##/####";
MaskFormatter maskFormatter = null;
try {
maskFormatter = new MaskFormatter(maskFormat);
} catch (Exception exc) {
exc.printStackTrace();
}
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.

File: EmployeeDialog.java

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;
}

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

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();	
...
}

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

File: EmployeeDAO.java

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

Share


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

Share