DAO stands for Data Access Object pattern. Data Access Object in java is a design pattern used in software engineering to abstract and encapsulate all the database operations in a separate layer. The main purpose of the DAO pattern is to isolate the application/business layer from the persistence layer (usually a relational database, but could be any data source).
Crud operations with database
To manage the database operations, we use the DAO pattern. The DAO in java abstracts the database interactions, making our application more modular and maintainable.
Here are the main steps to integrate the DAO pattern:
- DAO Interface: Define an interface with methods for CRUD (Create, Read, Update, Delete) operations.
- DAO Implementation: Provide the concrete implementation of the DAO interface using JDBC or any other database connection mechanism.
- Employee: This class models employee data with attributes for number of tickets, ID, and name, along with methods for accessing and modifying these attributes.
- Main Class: Create the main class that initializes the GUI components and handles the user interactions.

NOTE
you can get this code from GitHub
Or By Downloading the zip file
DAO implementation
A Java class DAOimplementation
that implements the EmployeeDAO
interface, encapsulating crud operations with database for an employee
table, named aooplab
. This class includes methods for reading, inserting, updating, and deleting employee records, utilizing PreparedStatement
for secure and efficient SQL query execution. It connects to the database through a DB
utility class, handles possible SQL exceptions, and provides user feedback via JOptionPane
dialogs. The code ensures that the total number of tickets does not exceed a predefined limit and performs validation checks before database modifications.
import static java.sql.DriverManager.getConnection;
public class DAOimplementation implements EmployeeDAO{
public int read(employee employee,DB c)throws SQLException, ClassNotFoundException {
Connection connection=DB.getConnection();
int i=employee.id;
String n=employee.name;
if (employee.NoofTickets<=8){
PreparedStatement preparedStatement=connection.prepareStatement("Select no from aooplab where id=?");
preparedStatement.setInt(1,i);
ResultSet resultSet=preparedStatement.executeQuery();
int Current=resultSet.getInt(2);
if(employee.NoofTickets<=Current){
Current-=employee.NoofTickets;
PreparedStatement preparedStatement1=connection.prepareStatement("update aooplab set no=? where id=?");
preparedStatement1.setInt(1,Current);
preparedStatement1.setInt(2,employee.id);
preparedStatement1.execute();
return Current;
}
else {
JOptionPane.showMessageDialog(null, "Wrong no of tickets were Selected");
return -1;
}
}
return 0;
}
public int insert(employee employee,DB c)throws SQLException, ClassNotFoundException {
if(!checkTickets(employee.NoofTickets)){
return -1;
}
Connection connection=DB.getConnection();
int i=employee.id;
String n=employee.name;
String sql="insert into aooplab values(?,?,?)";
PreparedStatement ps=connection.prepareStatement(sql);
ps.setInt(3,employee.NoofTickets);
ps.setInt(2,i);
ps.setString(1,n);
int rowsAffected=ps.executeUpdate();
if(rowsAffected>0){
JOptionPane.showMessageDialog(null,"Data Inserted Successfully");
}else{
JOptionPane.showMessageDialog(null,"Error in database");
}
return 0;
}
private boolean checkTickets(int NoofTickets) throws SQLException, ClassNotFoundException {
Connection con = DB.getConnection();
PreparedStatement ps = con.prepareStatement("select NoofTickets from aooplab");
ResultSet rs = ps.executeQuery();
int tickets =0;
while(rs.next()){
tickets+= rs.getInt("NoofTickets");
}
if(NoofTickets+tickets >8){
JOptionPane.showMessageDialog(null,"You can't book more than 8 tickets");
return false;
}
return true;
}
public int update(employee employee,DB c)throws SQLException, ClassNotFoundException {
Connection connection=DB.getConnection();
int i=employee.id;
String n=employee.name;
String sql="UPDATE aooplab SET name = ? WHERE id = ?";
PreparedStatement ps1=connection.prepareStatement(sql);
ps1.setInt(2,i);
ps1.setString(1,n);
int rowsAffected=ps1.executeUpdate();
if(rowsAffected>0){
JOptionPane.showMessageDialog(null,"Data updated Successfully");
}else{
JOptionPane.showMessageDialog(null,"Error in database");
}
return 0;
}
@Override
public int delete(int id)throws SQLException, ClassNotFoundException {
Connection connection=DB.getConnection();
String sql = "DELETE FROM aooplab WHERE id = ?";
PreparedStatement ps1=connection.prepareStatement(sql);
ps1.setInt(1,id);
int rowsAffected=ps1.executeUpdate();
if(rowsAffected>0){
JOptionPane.showMessageDialog(null,"Data deleted Successfully");
}else{
JOptionPane.showMessageDialog(null,"Error in database");
}
return 0;
}
}

Database connection with IntelliJ
The D
atabase connection class in Java provides a utility for establishing connections to a MySQL database, facilitating interactions with an employee
database located on a local server. The class includes static fields that store the database driver class, connection URL, and authentication credentials (username and password). The primary method, getConnection()
, loads the MySQL JDBC driver and attempts to create a connection to the specified database using DriverManager
.
public class DB {
static String driver="com.mysql.cj.jdbc.Driver";
static String databaseurl="jdbc:mysql://localhost:3306/employee";
static String UN="root";
static String PS="password";
public DB() throws SQLException {
}
public static Connection getConnection( )throws SQLException,ClassNotFoundException{
Class.forName(driver);
Connection connection= DriverManager.getConnection(databaseurl,UN,PS);
System.out.println("Database connected");
return connection;
}
}
Login form with crud operations
The login form with crud operations is the employeeGUI
class that extends JFrame
to create a graphical user interface for managing employee records in a database. It includes various components such as text fields for entering employee details (name, ID, number of tickets), and buttons for inserting, updating, deleting, and reading records. These components are organized using GridBagLayout
for precise positioning within the panel. The “Insert” button triggers an action to insert new employee data into the database, validating input and handling exceptions for number formatting and database connectivity. Similarly, the “Delete” button initiates a database delete operation based on the provided employee ID. Error messages are displayed using JOptionPane
dialogs for user feedback.
class employeeGUI extends JFrame {
JPanel panel = new JPanel();
JLabel userName = new JLabel("Name:");
JLabel id = new JLabel("ID:");
JLabel NO = new JLabel("No:");
JTextField field1 = new JTextField(10);
JTextField field2 = new JTextField(10);
JTextField field = new JTextField(10);
JButton b1 = new JButton("Insert");
JButton b2 = new JButton("Update");
JButton b3 = new JButton("Delete");
JButton b4 = new JButton("Read");
public employeeGUI() {
// Set layout manager
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(10, 10, 10, 10); // Adding padding around components
// Adding userName JLabel and JTextField
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.LINE_END;
panel.add(userName, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.LINE_START;
panel.add(field1, gbc);
// Adding id JLabel and JTextField
gbc.gridx = 0;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.LINE_END;
panel.add(id, gbc);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.LINE_START;
panel.add(field2, gbc);
// Adding NO JLabel and JTextField
gbc.gridx = 0;
gbc.gridy = 2;
gbc.anchor = GridBagConstraints.LINE_END;
panel.add(NO, gbc);
gbc.gridx = 1;
gbc.gridy = 2;
gbc.anchor = GridBagConstraints.LINE_START;
panel.add(field, gbc);
// Adding buttons
gbc.gridx = 0;
gbc.gridy = 3;
gbc.anchor = GridBagConstraints.CENTER;
panel.add(b1, gbc);
gbc.gridx = 1;
gbc.gridy = 3;
gbc.anchor = GridBagConstraints.CENTER;
panel.add(b2, gbc);
gbc.gridx = 0;
gbc.gridy = 4;
gbc.anchor = GridBagConstraints.CENTER;
panel.add(b3, gbc);
gbc.gridx = 1;
gbc.gridy = 4;
gbc.anchor = GridBagConstraints.CENTER;
panel.add(b4, gbc);
// Set default close operation and add panel to frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(panel);
setSize(400, 300);
setTitle("Employee GUI");
setVisible(true);
// Action Listener for Insert button
b1.addActionListener(e -> {
try {
String name = field1.getText();
int id = Integer.parseInt(field2.getText());
employee emp = new employee(Integer.parseInt(field.getText()), id, name);
DAOimplementation daoImplementation = new DAOimplementation();
if (daoImplementation.insert(emp, new DB()) == -1) {
JOptionPane.showMessageDialog(this, "You can't book more than 8 tickets");
}
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(this, "Invalid number format", "Error", JOptionPane.ERROR_MESSAGE);
} catch (SQLException | ClassNotFoundException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "Database error: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
});
// Action Listener for Delete button
b3.addActionListener(e -> {
try {
int id = Integer.parseInt(field2.getText());
DAOimplementation daoImplementation = new DAOimplementation();
daoImplementation.delete(id);
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(this, "Invalid number format", "Error", JOptionPane.ERROR_MESSAGE);
} catch (SQLException | ClassNotFoundException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "Database error: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
});
}
}
Conclusion of DAO in java
Implementing DAO in Java with a database is essential for separating data access logic from business logic, promoting modularity, and ensuring efficient database operations. It improves code maintainability, scalability, and testability by encapsulating database interactions within DAO classes, adhering to principles of abstraction and separation of concerns.