📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
What is JDBC?
MySQL Connector/J
What will you learn?
- How to create the layout of a JavaFX application window using FXML.
- How to add UI controls like Text Field, Password Field, and Button.
- How to validate UI controls like Text Field, Password Field
- How to connect JavaFX application with MySQL database via JDBC API.
Tools and Technologies used
- JDK 1.8
- MySQL Connector Java - 8.0.13
- JDBC - 4.2
- Eclipse IDE
- JavaFX
Development steps
- Create a Simple Maven Project
- Add Dependencies
- Project Structure
- Database Setup
- Create the Main Application Class
- Create the Layout for Our Application using FXML
- Create a register controller to handle form data
- Create JDBCDao for Database operations
- Run application
- Output
1. Create a Simple Maven Project
2. Add Dependencies
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.javaguides.javafx</groupId>
<artifactId>javafx-registration-form-mysql-tutorial</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>javafx-registration-form-mysql-tutorial</name>
<description>javafx-registration-form-mysql-tutorial</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<mainClass>com.javaguides.javafx.registration.MainApp</mainClass>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
3. Project Structure
4. Database Setup
create database javafx_registration;
CREATE TABLE registration
(
id BIGINT PRIMARY KEY AUTO_INCREMENT,
full_name varchar(250) NOT NULL,
email_id varchar(250) NOT NULL,
password varchar(250)
);
5. Create the Main Application Class
package com.javaguides.javafx.registration;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class MainApp extends Application {
@Override
public void start(Stage stage) throws Exception {
System.out.println(getClass());
Parent root = FXMLLoader.load(getClass().getResource("/fxml/registration_form.fxml"));
stage.setTitle("User Registration");
stage.setScene(new Scene(root, 800, 500));
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
6. Create the Layout for Our Application using FXML
<?import javafx.scene.layout.GridPane?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.text.Font?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.control.PasswordField?>
<?import javafx.scene.control.Button?>
<GridPane fx:controller="com.javaguides.javafx.registration.RegisterController"
xmlns:fx="http://javafx.com/fxml" alignment="center"
hgap="10" vgap="10">
<padding>
<Insets top="40" right="40" bottom="40" left="40"/>
</padding>
<columnConstraints>
<ColumnConstraints minWidth="100" prefWidth="100"
maxWidth="Infinity" halignment="RIGHT"></ColumnConstraints>
<ColumnConstraints minWidth="200" prefWidth="200"
maxWidth="Infinity" hgrow="ALWAYS"></ColumnConstraints>
</columnConstraints>
<!-- Add Header Label -->
<Label text="Registration Form (FXML)" GridPane.columnIndex="0"
GridPane.rowIndex="0" GridPane.columnSpan="2"
GridPane.rowSpan="1" GridPane.halignment="CENTER" >
<font>
<Font name="Arial" size="24" ></Font>
</font>
<GridPane.margin>
<Insets top="20" right="0" bottom="20" left="0"></Insets>
</GridPane.margin>
</Label>
<!-- Add Name Label -->
<Label text="Full Name : " GridPane.columnIndex="0"
GridPane.rowIndex="1" ></Label>
<!-- Add Name Text Field -->
<TextField fx:id="fullNameField" prefHeight="40"
GridPane.columnIndex="1" GridPane.rowIndex="1"/>
<!-- Add Email Label -->
<Label text="Email ID : " GridPane.columnIndex="0"
GridPane.rowIndex="2" ></Label>
<!-- Add Email Text Field -->
<TextField fx:id="emailIdField" prefHeight="40"
GridPane.columnIndex="1" GridPane.rowIndex="2"/>
<!-- Add Password Label -->
<Label text="Password : " GridPane.columnIndex="0"
GridPane.rowIndex="3" ></Label>
<!-- Add Password Field -->
<PasswordField fx:id="passwordField" prefHeight="40"
GridPane.columnIndex="1" GridPane.rowIndex="3"/>
<!-- Add Submit Button -->
<Button fx:id="submitButton" text="Submit"
prefWidth="100" prefHeight="40" defaultButton="true"
GridPane.columnIndex="0" GridPane.rowIndex="4"
GridPane.columnSpan="2" GridPane.rowSpan="1"
GridPane.halignment="CENTER"
onAction="#register">
<GridPane.margin>
<Insets top="20" right="0" bottom="20" left="0"></Insets>
</GridPane.margin>
</Button>
</GridPane>
7. Create a register controller to handle form data
package com.javaguides.javafx.registration;
import java.sql.SQLException;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.stage.Window;
public class RegisterController {
@FXML
private TextField fullNameField;
@FXML
private TextField emailIdField;
@FXML
private PasswordField passwordField;
@FXML
private Button submitButton;
@FXML
public void register(ActionEvent event) throws SQLException {
Window owner = submitButton.getScene().getWindow();
System.out.println(fullNameField.getText());
System.out.println(emailIdField.getText());
System.out.println(passwordField.getText());
if (fullNameField.getText().isEmpty()) {
showAlert(Alert.AlertType.ERROR, owner, "Form Error!",
"Please enter your name");
return;
}
if (emailIdField.getText().isEmpty()) {
showAlert(Alert.AlertType.ERROR, owner, "Form Error!",
"Please enter your email id");
return;
}
if (passwordField.getText().isEmpty()) {
showAlert(Alert.AlertType.ERROR, owner, "Form Error!",
"Please enter a password");
return;
}
String fullName = fullNameField.getText();
String emailId = emailIdField.getText();
String password = passwordField.getText();
JdbcDao jdbcDao = new JdbcDao();
jdbcDao.insertRecord(fullName, emailId, password);
showAlert(Alert.AlertType.CONFIRMATION, owner, "Registration Successful!",
"Welcome " + fullNameField.getText());
}
private static void showAlert(Alert.AlertType alertType, Window owner, String title, String message) {
Alert alert = new Alert(alertType);
alert.setTitle(title);
alert.setHeaderText(null);
alert.setContentText(message);
alert.initOwner(owner);
alert.show();
}
}
8. Create JDBCDao for Database operations
- Establishing a connection
- Create a statement
- Execute the query
- Using try-with-resources Statements to Automatically Close JDBC Resources
Connection conn = DriverManager.getConnection(Urldatabase,Username,Password);
package com.javaguides.javafx.registration;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JdbcDao {
// Replace below database url, username and password with your actual database credentials
private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/javafx_registration?useSSL=false";
private static final String DATABASE_USERNAME = "root";
private static final String DATABASE_PASSWORD = "root";
private static final String INSERT_QUERY = "INSERT INTO registration (full_name, email_id, password) VALUES (?, ?, ?)";
public void insertRecord(String fullName, String emailId, String password) throws SQLException {
// Step 1: Establishing a Connection and
// try-with-resource statement will auto close the connection.
try (Connection connection = DriverManager
.getConnection(DATABASE_URL, DATABASE_USERNAME, DATABASE_PASSWORD);
// Step 2:Create a statement using connection object
PreparedStatement preparedStatement = connection.prepareStatement(INSERT_QUERY)) {
preparedStatement.setString(1, fullName);
preparedStatement.setString(2, emailId);
preparedStatement.setString(3, password);
System.out.println(preparedStatement);
// Step 3: Execute the query or update query
preparedStatement.executeUpdate();
} catch (SQLException e) {
// print SQL exception information
printSQLException(e);
}
}
public static void printSQLException(SQLException ex) {
for (Throwable e: ex) {
if (e instanceof SQLException) {
e.printStackTrace(System.err);
System.err.println("SQLState: " + ((SQLException) e).getSQLState());
System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
System.err.println("Message: " + e.getMessage());
Throwable t = ex.getCause();
while (t != null) {
System.out.println("Cause: " + t);
t = t.getCause();
}
}
}
}
}
Comments
Post a Comment
Leave Comment