Connection Class//Establish Connection
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package tryjdbc1;
import java.sql.*;
import javax.swing.JOptionPane;
/**
* @author deebi
*/
public class GetConnection {
public static Connection conn(){
try {
// Establish JDBC connection
String url = "jdbc:mysql://localhost:3306/trydb1";
String username = "root";
String password = "";
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, username, password);
//return conn;
System.out.println("Connected to database successfully!");
} catch (SQLException|ClassNotFoundException ex) {
System.out.println("Failed to connect to database.");
// JOptionPane.showMessageDialog(null, ex);
return null;
public static void main(String[] args) {
conn();
Main Class
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Main.java to edit this template
*/
package tryjdbc1;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
/**
* @author deebi
*/
public class Tryjdbc1 {
//Components
JLabel fullNameLabel = new JLabel("Full Name");
JTextField fullName = new JTextField(20);
JLabel userNameLabel = new JLabel("Username");
JTextField userName = new JTextField(20);
JLabel passwordLabel = new JLabel("Password");
JPasswordField password = new JPasswordField(20);
JLabel ageLabel = new JLabel("Age");
JTextField age = new JTextField(10);
JButton submitBtn = new JButton("Submit");
JButton showBtn = new JButton("Show");
JButton updateBtn = new JButton("Update");
JButton deletBtn = new JButton("Delete");
JButton clearBtn = new JButton("Clear");
JComboBox<Object> searchInfo = new JComboBox<>();
JButton searchBtn = new JButton("Search");
// Create column names
String[] columnNames = {"ID", "Full Name", "Username", "Age"};
// Create data for the table (empty for now)
Object[][] data = {};
// Create a JTable with the specified data and column names
JTable table = new JTable(data, columnNames);
PreparedStatement pst;
ResultSet rs;
public Tryjdbc1() {
loadUSer();
fetch();
JFrame f = new JFrame("JDBC Example");
f.setLayout(new BorderLayout());
JPanel left = new JPanel();
JPanel top = new JPanel();
JPanel center = new JPanel();
JPanel right = new JPanel();
JPanel bottom = new JPanel();
top.setLayout(new FlowLayout());
center.setLayout(new FlowLayout());
bottom.setLayout(new FlowLayout());
// Set table properties
table.setPreferredScrollableViewportSize(new Dimension(500, 200));
table.setFillsViewportHeight(true);
// Add the table to a JScrollPane
JScrollPane scrollPane = new JScrollPane(table);
f.add(top, BorderLayout.NORTH);
f.add(center, BorderLayout.CENTER);
f.add(bottom, BorderLayout.SOUTH);
top.add(searchInfo);
top.add(searchBtn);
center.add(fullNameLabel);
center.add(fullName);
center.add(userNameLabel);
center.add(userName);
center.add(passwordLabel);
center.add(password);
center.add(ageLabel);
center.add(age);
// Add the JScrollPane to the Panel
center.add(scrollPane);
bottom.add(submitBtn);
bottom.add(showBtn);
bottom.add(updateBtn);
bottom.add(deletBtn);
bottom.add(clearBtn);
submitBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
insertData();
});
updateBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateData();
});
deletBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
deleteData();
});
searchBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
String selectedItem = searchInfo.getSelectedItem().toString();
String sql = "select * from accounts where id=?";
pst = GetConnection.conn().prepareStatement(sql);
// Set parameter value before executing the query
pst.setString(1, selectedItem);
rs = pst.executeQuery();
if (rs.next() == true) {
fullName.setText(rs.getString(2));
userName.setText(rs.getString(3));
password.setText(rs.getString(4));
age.setText(rs.getString(5));
} catch (SQLException ex) {
ex.printStackTrace();
});
f.setSize(320, 300);
f.setVisible(true);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
public void loadUSer()
try {
String loadU = "select id from accounts";
pst = GetConnection.conn().prepareStatement(loadU);
rs = pst.executeQuery();
searchInfo.removeAllItems();
while(rs.next()) {
searchInfo.addItem(rs.getString(1));
} catch (Exception ex) {
//print the stack trace of an exception to the standard error stream.
ex.printStackTrace();
private void fetch()
try {
int count;
String sql = "select * from accounts";
pst = GetConnection.conn().prepareStatement(sql);
rs = pst.executeQuery();
ResultSetMetaData rsm = rs.getMetaData();
count = rsm.getColumnCount();
DefaultTableModel df = new DefaultTableModel(); // Create a new DefaultTableModel
for (int i = 1; i <= count; i++) {
df.addColumn(rsm.getColumnName(i)); // Add columns based on ResultSetMetaData
while (rs.next()) {
Vector<String> row = new Vector<>();
for (int i = 1; i <= count; i++) {
row.add(rs.getString(i)); // Add data from ResultSet to Vector
df.addRow(row); // Add Vector as a row to the DefaultTableModel
// Set the DefaultTableModel to the JTable
table.setModel(df);
} catch (SQLException ex) {
Logger.getLogger(Tryjdbc1.class.getName()).log(Level.SEVERE, null, ex);
public void insertData()
{
try {
//get a data from the field
String name = fullName.getText();
String uname = userName.getText();
char[] passChars = password.getPassword();
String pass = new String(passChars);
String ageStr = age.getText();
int ageParse = Integer.parseInt(ageStr);
//insert into database
String sql = "insert into accounts(fullname, username, password, age) value(?,?,?,?)";
pst = GetConnection.conn().prepareStatement(sql);
//lets pass a value
pst.setString(1, name);
pst.setString(2, uname);
pst.setString(3, pass);
pst.setInt(4, ageParse);
int r = pst.executeUpdate();
if(r==1)
JOptionPane.showMessageDialog(null, "Data Inserted Succcessfully");
//after insertion successfull
fullName.setText("");
userName.setText("");
password.setText("");
age.setText("");
fullName.requestFocus();
fetch();
loadUSer();
else
JOptionPane.showMessageDialog(null, "Failed to save a record");
} catch (SQLException ex) {
ex.printStackTrace();
public void updateData()
try {
String selectedItem = searchInfo.getSelectedItem().toString();
String updateName = fullName.getText();
String updateUsername = userName.getText();
char[] passCharsUpdate = password.getPassword();
String updatePass = new String(passCharsUpdate);
String ageStrUpdate = age.getText();
//int ageParseUpdate = Integer.parseInt(ageStrUpdate);
String sql = "update accounts set fullname = ?, username = ?, password = ?, age = ? where id = ?;";
pst = GetConnection.conn().prepareStatement(sql);
pst.setString(1, updateName);
pst.setString(2, updateUsername);
pst.setString(3, updatePass);
pst.setString(4, ageStrUpdate);
pst.setString(5, selectedItem);
int r = pst.executeUpdate();
if(r == 1){
JOptionPane.showMessageDialog(null, "Record Updated Successfully");
//after update successfull
fullName.setText("");
userName.setText("");
password.setText("");
age.setText("");
fullName.requestFocus(); //focus
fetch();
loadUSer();//Load user info
else{
JOptionPane.showMessageDialog(null, "Error occured on Update");
}
} catch (Exception ex) {
ex.printStackTrace();
public void deleteData()
try {
String selectedItem = searchInfo.getSelectedItem().toString();
String sql = "delete from accounts where id=?";
pst = GetConnection.conn().prepareStatement(sql);
pst.setString(1, selectedItem);
int r = pst.executeUpdate();
if(r == 1)
JOptionPane.showMessageDialog(null, "Record Deleted Successfully");
//after delete successfull
fullName.setText("");
userName.setText("");
password.setText("");
age.setText("");
fullName.requestFocus(); //focus
fetch();
loadUSer();//Load user info
}
else
JOptionPane.showMessageDialog(null, "Error occured on delete");
} catch (SQLException ex) {
ex.printStackTrace();
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Tryjdbc1();