0% found this document useful (0 votes)
199 views26 pages

Java Crud Code

This document contains code for a Java GUI application that allows users to perform CRUD (create, read, update, delete) operations on a database. It includes code to define form fields, buttons, and tables to display, add, edit and delete database records. The application connects to a database using JDBC and executes SQL statements to perform the CRUD operations.

Uploaded by

leinadmofficial
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
199 views26 pages

Java Crud Code

This document contains code for a Java GUI application that allows users to perform CRUD (create, read, update, delete) operations on a database. It includes code to define form fields, buttons, and tables to display, add, edit and delete database records. The application connects to a database using JDBC and executes SQL statements to perform the CRUD operations.

Uploaded by

leinadmofficial
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

/*

* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license

* Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template

*/

package crud;

//import com.sun.jdi.connect.spi.Connection;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.Statement;

import java.sql.*;

import javax.swing.JFrame;

import javax.swing.JOptionPane;

import static javax.swing.JOptionPane.showMessageDialog;

import javax.swing.table.DefaultTableModel;

/**

* @author leina

*/

public class View extends javax.swing.JFrame {


/**

* Creates new form View

*/

public View() {

initComponents();

/**

* This method is called from within the constructor to initialize the form.

* WARNING: Do NOT modify this code. The content of this method is always

* regenerated by the Form Editor.

*/

@SuppressWarnings("unchecked")

// <editor-fold defaultstate="collapsed" desc="Generated Code">

private void initComponents() {

jPanel1 = new javax.swing.JPanel();

jLabel1 = new javax.swing.JLabel();

fName = new javax.swing.JTextField();

jLabel2 = new javax.swing.JLabel();

lName = new javax.swing.JTextField();

jLabel3 = new javax.swing.JLabel();


email = new javax.swing.JTextField();

submit = new javax.swing.JButton();

jLabel4 = new javax.swing.JLabel();

jSeparator1 = new javax.swing.JSeparator();

Clear = new javax.swing.JButton();

delete = new javax.swing.JButton();

update = new javax.swing.JButton();

searchData = new javax.swing.JTextField();

jLabel5 = new javax.swing.JLabel();

searchBtn = new javax.swing.JButton();

jScrollPane1 = new javax.swing.JScrollPane();

Table = new javax.swing.JTable();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

setTitle("DANIEL CRUD PURE JAVA APPLICATION");

setPreferredSize(new java.awt.Dimension(1000, 1000));

jPanel1.setBackground(new java.awt.Color(255, 255, 255));

jPanel1.setPreferredSize(new java.awt.Dimension(1000, 300));

jLabel1.setText("First Name");

fName.setBackground(new java.awt.Color(204, 204, 204));


fName.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

fNameActionPerformed(evt);

});

jLabel2.setText("Last Name");

lName.setBackground(new java.awt.Color(204, 204, 204));

lName.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

lNameActionPerformed(evt);

});

jLabel3.setText("Email");

email.setBackground(new java.awt.Color(204, 204, 204));

email.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

emailActionPerformed(evt);

});
submit.setBackground(new java.awt.Color(51, 153, 255));

submit.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N

submit.setForeground(new java.awt.Color(255, 255, 255));

submit.setText("Submit");

submit.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

submitActionPerformed(evt);

});

jLabel4.setFont(new java.awt.Font("Segoe UI", 1, 36)); // NOI18N

jLabel4.setForeground(new java.awt.Color(0, 0, 0));

jLabel4.setText("JAVA CRUD APPLICATION BY DANIEL MOYO");

Clear.setText("Clear");

Clear.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

ClearActionPerformed(evt);

});

delete.setBackground(new java.awt.Color(204, 0, 51));


delete.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N

delete.setForeground(new java.awt.Color(255, 255, 255));

delete.setText("Delete");

delete.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

deleteActionPerformed(evt);

});

update.setBackground(new java.awt.Color(255, 204, 0));

update.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N

update.setForeground(new java.awt.Color(0, 0, 0));

update.setText("Update");

update.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

updateActionPerformed(evt);

});

searchData.setBackground(new java.awt.Color(204, 204, 204));

searchData.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

searchDataActionPerformed(evt);
}

});

jLabel5.setText("Search By ID");

searchBtn.setBackground(new java.awt.Color(51, 255, 0));

searchBtn.setForeground(new java.awt.Color(0, 0, 0));

searchBtn.setText("Search");

searchBtn.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

searchBtnActionPerformed(evt);

});

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);

jPanel1.setLayout(jPanel1Layout);

jPanel1Layout.setHorizontalGroup(

jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING)

.addGroup(jPanel1Layout.createSequentialGroup()

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(jPanel1Layout.createSequentialGroup()

.addGap(28, 28, 28)


.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 1115, javax.swing.GroupLayout.PREFERRED_SIZE))

.addGroup(jPanel1Layout.createSequentialGroup()

.addGap(37, 37, 37)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(jPanel1Layout.createSequentialGroup()

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(fName, javax.swing.GroupLayout.PREFERRED_SIZE, 241, javax.swing.GroupLayout.PREFERRED_SIZE))

.addGap(18, 18, 18)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addComponent(lName, javax.swing.GroupLayout.PREFERRED_SIZE, 256, javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)))

.addGroup(jPanel1Layout.createSequentialGroup()

.addComponent(submit, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)

.addGap(18, 18, 18)

.addComponent(update, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)

.addGap(18, 18, 18)

.addComponent(delete, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)

.addGap(18, 18, 18)

.addComponent(Clear, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)))

.addGap(31, 31, 31)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)

.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(email, javax.swing.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE)

.addComponent(searchData))

.addGap(18, 18, 18)

.addComponent(searchBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE))

.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))))

.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))

);

jPanel1Layout.setVerticalGroup(

jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(jPanel1Layout.createSequentialGroup()

.addGap(31, 31, 31)

.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)

.addGap(18, 18, 18)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(jLabel1)

.addComponent(jLabel2)

.addComponent(jLabel3))

.addGap(18, 18, 18)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(fName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(lName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,


javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(email, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,


javax.swing.GroupLayout.PREFERRED_SIZE))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

.addComponent(jLabel5)

.addGap(3, 3, 3)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(submit, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(update, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(delete, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(Clear, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(searchBtn)

.addComponent(searchData, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))

.addContainerGap(28, Short.MAX_VALUE))

);

jScrollPane1.setPreferredSize(new java.awt.Dimension(1000, 600));

Table.setBackground(new java.awt.Color(255, 255, 255));

Table.setForeground(new java.awt.Color(0, 0, 0));

Table.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {

{null, null, null, null},

{null, null, null, null},

{null, null, null, null},

{null, null, null, null}

},

new String [] {

"ID", "First Name", "Last Name", "Email"

) {

Class[] types = new Class [] {

java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class

};

boolean[] canEdit = new boolean [] {

false, false, false, false

};

public Class getColumnClass(int columnIndex) {

return types [columnIndex];

public boolean isCellEditable(int rowIndex, int columnIndex) {

return canEdit [columnIndex];


}

});

jScrollPane1.setViewportView(Table);

if (Table.getColumnModel().getColumnCount() > 0) {

Table.getColumnModel().getColumn(0).setMaxWidth(50);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());

getContentPane().setLayout(layout);

layout.setHorizontalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addContainerGap()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 1012, javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,


javax.swing.GroupLayout.PREFERRED_SIZE))

.addContainerGap(1012, Short.MAX_VALUE))

);

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)

.addGap(0, 0, Short.MAX_VALUE))

);

pack();

}// </editor-fold>

private void fNameActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

private void lNameActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

private void emailActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

public void loadData() {

//DB connection

try {
Class.forName("com.mysql.cj.jdbc.Driver");

String url = "jdbc:MySQL://localhost:3306/crud";

String user = "root";

String password = "";

Connection con = DriverManager.getConnection(url, user, password);

Statement st = con.createStatement();

DefaultTableModel model = new DefaultTableModel(new String[]{"ID", "First Name", "Last Name", "Email"}, 0);

Table.setModel(model);

String sql = "SELECT * FROM user ORDER BY id DESC";

ResultSet rs = st.executeQuery(sql);

String i, f, l, e;

while (rs.next()) {

i = rs.getString("id");

f = rs.getString("first_name");

l = rs.getString("last_name");

e = rs.getString("email");

model.addRow(new Object[]{i, f, l, e});


}

} catch (Exception e) {

System.out.println("Error" + e.getMessage());

private void submitActionPerformed(java.awt.event.ActionEvent evt) {

String fN, lN, em, query;

//connect to the database

try {

Class.forName("com.mysql.cj.jdbc.Driver");

String url = "jdbc:MySQL://localhost:3306/crud";

String user = "root";

String password = "";

Connection con = DriverManager.getConnection(url, user, password);

Statement st = con.createStatement();

//Error handlers
if ("".equals(fName.getText())) {

JOptionPane.showMessageDialog(new JFrame(), "First Name is required", "ERROR", JOptionPane.ERROR_MESSAGE);

} else if ("".equals(lName.getText())) {

JOptionPane.showMessageDialog(new JFrame(), "Last Name is required", "ERROR", JOptionPane.ERROR_MESSAGE);

} else if ("".equals(email.getText())) {

JOptionPane.showMessageDialog(new JFrame(), "Email is required", "ERROR", JOptionPane.ERROR_MESSAGE);

} else {

fN = fName.getText();

lN = lName.getText();

em = email.getText();

query = "INSERT INTO user (first_name, last_name, email) " + "VALUES ('" + fN + "','" + lN + "','" + em + "')";

st.executeUpdate(query);

fName.setText("");

lName.setText("");

email.setText("");

//JOptionPane.showMessageDialog(new JFrame(), "Data saved successfully", "SUCCESS", JOptionPane.OK_OPTION);

showMessageDialog(null, "Successfully Registered.");

loadData();

con.close();
//System.out.println(query);

} catch (Exception e) {

System.out.println("Error" + e.getMessage());

//System.out.println(fN);

private void updateActionPerformed(java.awt.event.ActionEvent evt) {

String ID;

int notFound = 0;

String fN, lN, em;

try {

Class.forName("com.mysql.cj.jdbc.Driver");

String url = "jdbc:MySQL://localhost:3306/crud";

String user = "root";

String password = "";


Connection con = DriverManager.getConnection(url, user, password);

Statement st = con.createStatement();

ID = searchData.getText();

//Error handlers

if ("".equals(ID)) {

JOptionPane.showMessageDialog(new JFrame(), "ID is required", "ERROR", JOptionPane.ERROR_MESSAGE);

} else {

String sql = "SELECT * FROM user WHERE id=" + ID;

ResultSet rs = st.executeQuery(sql);

while (rs.next()) {

notFound = 1;

fN = fName.getText();

lN = lName.getText();

em = email.getText();

String sql2 = "UPDATE user SET first_name='" + fN + "', last_name='" + lN + "', email='" + em + "' WHERE id =" + ID;

st.executeUpdate(sql2);

loadData();

con.close();

}
if (notFound == 0) {

JOptionPane.showMessageDialog(new JFrame(), "Record not found", "ERROR", JOptionPane.ERROR_MESSAGE);

} catch (Exception e) {

System.out.println("Error" + e.getMessage());

private void deleteActionPerformed(java.awt.event.ActionEvent evt) {

String ID;

int notFound = 0;

try {

Class.forName("com.mysql.cj.jdbc.Driver");

String url = "jdbc:MySQL://localhost:3306/crud";

String user = "root";

String password = "";

Connection con = DriverManager.getConnection(url, user, password);


Statement st = con.createStatement();

ID = searchData.getText();

//Error handlers

if ("".equals(ID)) {

JOptionPane.showMessageDialog(new JFrame(), "ID is required", "ERROR", JOptionPane.ERROR_MESSAGE);

} else {

String sql = "SELECT * FROM user WHERE id=" + ID;

ResultSet rs = st.executeQuery(sql);

while (rs.next()) {

notFound = 1;

String sql2 = "DELETE FROM user WHERE id=" + ID;

st.executeUpdate(sql2);

loadData();

con.close();

if (notFound == 0) {

JOptionPane.showMessageDialog(new JFrame(), "Record not found", "ERROR", JOptionPane.ERROR_MESSAGE);

}
} catch (Exception e) {

System.out.println("Error" + e.getMessage());

private void searchBtnActionPerformed(java.awt.event.ActionEvent evt) {

//Search Button action code

String ID;

int notFound = 0;

try {

Class.forName("com.mysql.cj.jdbc.Driver");

String url = "jdbc:MySQL://localhost:3306/crud";

String user = "root";

String password = "";

Connection con = DriverManager.getConnection(url, user, password);

Statement st = con.createStatement();
ID = searchData.getText();

//Error handlers

if ("".equals(ID)) {

JOptionPane.showMessageDialog(new JFrame(), "ID is required", "ERROR", JOptionPane.ERROR_MESSAGE);

} else {

String sql = "SELECT * FROM user WHERE id=" + ID;

ResultSet rs = st.executeQuery(sql);

while (rs.next()) {

fName.setText(rs.getString("first_name"));

lName.setText(rs.getString("last_name"));

email.setText(rs.getString("email"));

notFound = 1;

con.close();

if (notFound == 0) {

JOptionPane.showMessageDialog(new JFrame(), "Record not found", "ERROR", JOptionPane.ERROR_MESSAGE);

} catch (Exception e) {
System.out.println("Error" + e.getMessage());

private void searchDataActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

private void ClearActionPerformed(java.awt.event.ActionEvent evt) {

fName.setText("");

lName.setText("");

email.setText("");

searchData.setText("");

/**

* @param args the command line arguments

*/

public static void main(String args[]) {

/* Set the Nimbus look and feel */

//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.

* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html

*/

try {

for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {

if ("Nimbus".equals(info.getName())) {

javax.swing.UIManager.setLookAndFeel(info.getClassName());

break;

} catch (ClassNotFoundException ex) {

java.util.logging.Logger.getLogger(View.class

.getName()).log(java.util.logging.Level.SEVERE, null, ex);

} catch (InstantiationException ex) {

java.util.logging.Logger.getLogger(View.class

.getName()).log(java.util.logging.Level.SEVERE, null, ex);

} catch (IllegalAccessException ex) {

java.util.logging.Logger.getLogger(View.class

.getName()).log(java.util.logging.Level.SEVERE, null, ex);


} catch (javax.swing.UnsupportedLookAndFeelException ex) {

java.util.logging.Logger.getLogger(View.class

.getName()).log(java.util.logging.Level.SEVERE, null, ex);

//</editor-fold>

/* Create and display the form */

java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {

View x = new View();

x.loadData();

x.setLocationRelativeTo(null);

x.setVisible(true);

});

// Variables declaration - do not modify

private javax.swing.JButton Clear;

private javax.swing.JTable Table;

private javax.swing.JButton delete;

private javax.swing.JTextField email;

private javax.swing.JTextField fName;


private javax.swing.JLabel jLabel1;

private javax.swing.JLabel jLabel2;

private javax.swing.JLabel jLabel3;

private javax.swing.JLabel jLabel4;

private javax.swing.JLabel jLabel5;

private javax.swing.JPanel jPanel1;

private javax.swing.JScrollPane jScrollPane1;

private javax.swing.JSeparator jSeparator1;

private javax.swing.JTextField lName;

private javax.swing.JButton searchBtn;

private javax.swing.JTextField searchData;

private javax.swing.JButton submit;

private javax.swing.JButton update;

// End of variables declaration

You might also like