0% found this document useful (0 votes)
0 views

MySQL operations in JAVA

The document provides a tutorial on performing CRUD operations (Create, Read, Update, Delete) using MySQL in a Java application with a Swing UI. It outlines the necessary software requirements, database setup, and detailed code snippets for each operation, including how to connect to the database, execute SQL commands, and update the UI accordingly. The final code is presented as a complete Java class for managing student records in a database.

Uploaded by

mikewasongah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

MySQL operations in JAVA

The document provides a tutorial on performing CRUD operations (Create, Read, Update, Delete) using MySQL in a Java application with a Swing UI. It outlines the necessary software requirements, database setup, and detailed code snippets for each operation, including how to connect to the database, execute SQL commands, and update the UI accordingly. The final code is presented as a complete Java class for managing student records in a database.

Uploaded by

mikewasongah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

MySQL operations in JAVA

Before you start, you need to have some requirements with you. Make sure you have all
these things.
1. NetBeans IDE (I prefer NetBeans because I’m using NetBeans in this tutorial)
2. JDBC connector.
3. Java 8.0 or upper version installed.
4. XAMPP installed.
Creating the UI using a java swing package
Let’s start creating the UI first. If you are using the NetBeans IDE just create an empty
JFrame and add the components as shown.

Creating the MySQL Database


In order to store the data from the system, you need to have a database. Using XAMPP
you can easily create your database. In this example, my database name is iit, and the
table name is record. You can see my database structure and you need to follow the exact
same way.
CREATE

What CREATE operation showed in this example is that storing the data which is given to the
student registration form (check UI). When you click the Add button those data will be saved to
the database. In this scenario Student name, Student ID, and Course name will be saved into the
database. Below I have mentioned the code sample for the CREATE operation. In the add button
the following code is added :
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

String name =txtname.getText();

String studentId =txtid.getText();

String course =txtcourse.getText();

try {

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

con1 = DriverManager.getConnection("jdbc:mysql://localhost/iit","root","");

insert = con1.prepareStatement("insert into record(name,studentid,course)values(?,?,?)");

insert.setString(1, name);

insert.setString(2, studentId);

insert.setString(3, course);

insert.executeUpdate();

JOptionPane.showMessageDialog(this,"Record Saved");

txtname.setText("");

txtid.setText("");

txtcourse.setText("");

txtname.requestFocus();

table_update();

} catch (ClassNotFoundException ex) {

Logger.getLogger(Registration.class.getName()).log(Level.SEVERE, null, ex);

} catch (SQLException ex) {

Logger.getLogger(Registration.class.getName()).log(Level.SEVERE, null, ex);

} }
READ
Once you perform the CREATE operation you can read back the data you created. In this
example, I’m reading back the data from the database and show it using a table. for the table, you
have to create the table in the following manner.
private void table_update() {
int CC;
try {
Class.forName("com.mysql.jdbc.Driver");
con1 = DriverManager.getConnection("jdbc:mysql://localhost/iit","root","");
insert = con1.prepareStatement("SELECT * FROM record");
ResultSet Rs = insert.executeQuery();
ResultSetMetaData RSMD = Rs.getMetaData();
CC = RSMD.getColumnCount();
DefaultTableModel DFT = (DefaultTableModel) table.getModel();
DFT.setRowCount(0);
while (Rs.next()) {
Vector v2 = new Vector();

for (int ii = 1; ii <= CC; ii++) {


v2.add(Rs.getString("id"));
v2.add(Rs.getString("name"));
v2.add(Rs.getString("studentid"));
v2.add(Rs.getString("course"));
}
DFT.addRow(v2);
}
} catch (Exception e) {
}
}
UPDATE
Once you enter the record you may need to edit it. Using the UPDATE function, you can edit the
records in your database. Add the following code to the update button to perform the UPDATE
function.
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//update function
DefaultTableModel model = (DefaultTableModel) table.getModel();
int selectedIndex = table.getSelectedRow();
try {
int id = Integer.parseInt(model.getValueAt(selectedIndex, 0).toString());
String name =txtname.getText();
String studentId =txtid.getText();
String course =txtcourse.getText();
Class.forName("com.mysql.jdbc.Driver");
con1 = DriverManager.getConnection("jdbc:mysql://localhost/iit","root","");
insert = con1.prepareStatement("update record set name= ?,studentid= ?,course= ? where
id= ?");
insert.setString(1,name);
insert.setString(2,studentId);
insert.setString(3,course);
insert.setInt(4,id);
insert.executeUpdate();
JOptionPane.showMessageDialog(this, "Record Updated");
txtname.setText("");
txtid.setText("");
txtcourse.setText("");
table_update();
} catch (ClassNotFoundException ex) {
} catch (SQLException ex) {
}
}

DELETE
At last, this is how you delete the records in your database. You can remove the records by
selecting them from the table and using the delete button. Add this code to the delete button in
your UI.
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// Delete function
DefaultTableModel model = (DefaultTableModel) table.getModel();
int selectedIndex = table.getSelectedRow();
try {
int id = Integer.parseInt(model.getValueAt(selectedIndex, 0).toString());
int dialogResult = JOptionPane.showConfirmDialog (null, "Do you want to Delete the
record","Warning",JOptionPane.YES_NO_OPTION);
if(dialogResult == JOptionPane.YES_OPTION){
Class.forName("com.mysql.jdbc.Driver");
con1 = DriverManager.getConnection("jdbc:mysql://localhost/iit","root","");
insert = con1.prepareStatement("delete from record where id = ?");
insert.setInt(1,id);
insert.executeUpdate();
JOptionPane.showMessageDialog(this, "Record Delete");
txtname.setText("");
txtid.setText("");
txtcourse.setText("");
table_update();
}
} catch (ClassNotFoundException ex) {
} catch (SQLException ex) {
}
}

The final code output is as follows:


import javax.swing.JOptionPane;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

public class Registration extends javax.swing.JFrame {


public Registration() {
initComponents();
table_update();
}
Connection con1;
PreparedStatement insert;
private void table_update() {
int CC;
try {
Class.forName("com.mysql.jdbc.Driver");
con1 = DriverManager.getConnection("jdbc:mysql://localhost/iit","root","");
insert = con1.prepareStatement("SELECT * FROM record");
ResultSet Rs = insert.executeQuery();

ResultSetMetaData RSMD = Rs.getMetaData();


CC = RSMD.getColumnCount();
DefaultTableModel DFT = (DefaultTableModel) table.getModel();
DFT.setRowCount(0);
while (Rs.next()) {
Vector v2 = new Vector();

for (int ii = 1; ii <= CC; ii++) {


v2.add(Rs.getString("id"));
v2.add(Rs.getString("name"));
v2.add(Rs.getString("studentid"));
v2.add(Rs.getString("course"));
}
DFT.addRow(v2);
}
} catch (Exception e) {
}
}
private void initComponents() {………..}
private void txtnameActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}

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


// TODO add your handling code here:
}

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


// TODO add your handling code here:
String name =txtname.getText();
String studentId =txtid.getText();
String course =txtcourse.getText();
try {
Class.forName("com.mysql.jdbc.Driver");
con1 = DriverManager.getConnection("jdbc:mysql://localhost/iit","root","");
insert = con1.prepareStatement("insert into record(name,studentid,course)values(?,?,?)");
insert.setString(1, name);
insert.setString(2, studentId);
insert.setString(3, course);
insert.executeUpdate();

JOptionPane.showMessageDialog(this,"Record Saved");

txtname.setText("");
txtid.setText("");
txtcourse.setText("");
txtname.requestFocus();
table_update();

} catch (ClassNotFoundException ex) {


Logger.getLogger(Registration.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Registration.class.getName()).log(Level.SEVERE, null, ex);
}
}

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


// TODO add your handling code here:
// Delete function
DefaultTableModel model = (DefaultTableModel) table.getModel();
int selectedIndex = table.getSelectedRow();
try {

int id = Integer.parseInt(model.getValueAt(selectedIndex, 0).toString());


int dialogResult = JOptionPane.showConfirmDialog (null, "Do you want to Delete the
record","Warning",JOptionPane.YES_NO_OPTION);
if(dialogResult == JOptionPane.YES_OPTION){
Class.forName("com.mysql.jdbc.Driver");
con1 = DriverManager.getConnection("jdbc:mysql://localhost/iit","root","");
insert = con1.prepareStatement("delete from record where id = ?");

insert.setInt(1,id);
insert.executeUpdate();
JOptionPane.showMessageDialog(this, "Record Delete");
txtname.setText("");
txtid.setText("");
txtcourse.setText("");
table_update();
}
} catch (ClassNotFoundException ex) {
} catch (SQLException ex) {
}
}

private void tableMouseClicked(java.awt.event.MouseEvent evt) {


// TODO add your handling code here:
DefaultTableModel DFT = (DefaultTableModel) table.getModel();
int selectedRow = table.getSelectedRow();

txtname.setText(DFT.getValueAt(selectedRow, 1).toString());
txtid.setText(DFT.getValueAt(selectedRow, 2).toString());
txtcourse.setText(DFT.getValueAt(selectedRow, 3).toString());
}

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


// TODO add your handling code here:
//update function
DefaultTableModel model = (DefaultTableModel) table.getModel();
int selectedIndex = table.getSelectedRow();
try {

int id = Integer.parseInt(model.getValueAt(selectedIndex, 0).toString());


String name =txtname.getText();
String studentId =txtid.getText();
String course =txtcourse.getText();

Class.forName("com.mysql.jdbc.Driver");
con1 = DriverManager.getConnection("jdbc:mysql://localhost/iit","root","");
insert = con1.prepareStatement("update record set name= ?,studentid= ?,course= ? where
id= ?");
insert.setString(1,name);
insert.setString(2,studentId);
insert.setString(3,course);
insert.setInt(4,id);
insert.executeUpdate();
JOptionPane.showMessageDialog(this, "Record Updated");
txtname.setText("");
txtid.setText("");
txtcourse.setText("");
table_update();

} catch (ClassNotFoundException ex) {

} catch (SQLException ex) {


}

/**
* @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(Registration.class.getName()).log(java.util.logging.Level.SE
VERE, null, ex);
} catch (InstantiationException ex) {

java.util.logging.Logger.getLogger(Registration.class.getName()).log(java.util.logging.Level.SE
VERE, null, ex);
} catch (IllegalAccessException ex) {

java.util.logging.Logger.getLogger(Registration.class.getName()).log(java.util.logging.Level.SE
VERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {

java.util.logging.Logger.getLogger(Registration.class.getName()).log(java.util.logging.Level.SE
VERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Registration().setVisible(true);
}
});
}

// Variables declaration - do not modify


private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable table;
private javax.swing.JTextField txtcourse;
private javax.swing.JTextField txtid;
private javax.swing.JTextField txtname;
// End of variables declaration
}

You might also like