MySQL operations in JAVA
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.
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) {
try {
Class.forName("com.mysql.jdbc.Driver");
con1 = DriverManager.getConnection("jdbc:mysql://localhost/iit","root","");
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();
} }
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();
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) {
}
}
JOptionPane.showMessageDialog(this,"Record Saved");
txtname.setText("");
txtid.setText("");
txtcourse.setText("");
txtname.requestFocus();
table_update();
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) {
}
}
txtname.setText(DFT.getValueAt(selectedRow, 1).toString());
txtid.setText(DFT.getValueAt(selectedRow, 2).toString());
txtcourse.setText(DFT.getValueAt(selectedRow, 3).toString());
}
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();
/**
* @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);
}
});
}