this post we have look JAVA GUI - Database Connectivity.
Resource file: Database File (For Practical)
Code..
package javadatabasee;
import static com.sun.xml.internal.fastinfoset.alphabet.BuiltInRestrictedAlphabets.table;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
public class DataJFrame extends javax.swing.JFrame {
Connection con;
int id;
DefaultTableModel dataModel;
public DataJFrame() {
initComponents();
this.setLocationRelativeTo(null);
createConnection();
}
void createConnection(){
String url = "jdbc:mysql://localhost:3306/crud";
String username="root";
String pwd="";
try {
//Load the JDBC Driver
Class.forName("com.mysql.cj.jdbc.Driver");
//Establish the Database Connection
con = DriverManager.getConnection(url,username,pwd);
} catch (ClassNotFoundException ex) {
Logger.getLogger(DataJFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(DataJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jTextFieldName = new javax.swing.JTextField();
jButtonInsert = new javax.swing.JButton();
jTextFieldLocation = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
jTableData = new javax.swing.JTable();
jButtonRefresh = new javax.swing.JButton();
jButtonEdit = new javax.swing.JButton();
jButtonDelete = new javax.swing.JButton();
EditName = new javax.swing.JTextField();
EditLocation = new javax.swing.JTextField();
jButtonUpdate = new javax.swing.JButton();
jButtonClearAll = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButtonInsert.setText("Insert");
jButtonInsert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonInsertActionPerformed(evt);
}
});
jTableData.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"ID", "Name", "Location"
}
));
jScrollPane1.setViewportView(jTableData);
jButtonRefresh.setText("Refresh");
jButtonRefresh.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonRefreshActionPerformed(evt);
}
});
jButtonEdit.setText("Edit");
jButtonEdit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonEditActionPerformed(evt);
}
});
jButtonDelete.setText("Delete");
jButtonDelete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonDeleteActionPerformed(evt);
}
});
jButtonUpdate.setText("Update");
jButtonUpdate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonUpdateActionPerformed(evt);
}
});
jButtonClearAll.setText("Clear All");
jButtonClearAll.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonClearAllActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(15, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(EditName, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(EditLocation, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButtonUpdate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jTextFieldName, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTextFieldLocation, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButtonInsert, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButtonRefresh, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButtonEdit, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButtonDelete, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 388, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, Short.MAX_VALUE))))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButtonClearAll, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextFieldName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextFieldLocation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButtonInsert))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(EditName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EditLocation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButtonUpdate))
.addGap(11, 11, 11)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonRefresh)
.addComponent(jButtonEdit)
.addComponent(jButtonDelete))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButtonClearAll)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButtonInsertActionPerformed(java.awt.event.ActionEvent evt) {
String name=jTextFieldName.getText();
String loc=jTextFieldLocation.getText();
try {
/*Statement stmt = con.createStatement();
String query = "INSERT INTO data(name,location) VALUES('"+name+"','"+loc+"')";
stmt.execute(query);*/
PreparedStatement prst = con.prepareStatement("INSERT INTO data(name,location) VALUES(?,?)");
prst.setString(1,name);
prst.setString(2,loc);
prst.execute();
System.out.println("Insertion Completed!");
prst.close();
//stmt.close();
} catch (SQLException ex) {
Logger.getLogger(DataJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
jButtonClearAll.doClick();
jButtonRefresh.doClick();
}
private void jButtonRefreshActionPerformed(java.awt.event.ActionEvent evt) {
jButtonClearAll.doClick();
DefaultTableModel tableModel = (DefaultTableModel) jTableData.getModel();
try {
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery("SELECT * FROM data");
while(res.next()){
int id=res.getInt("id");
String name=res.getString("name");
String loc = res.getString("location");
tableModel.addRow(new Object[]{id,name,loc});
System.out.println(id+" "+name+" "+loc);
}
stmt.close();
} catch (SQLException ex) {
Logger.getLogger(DataJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void jButtonEditActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel) jTableData.getModel();
int no_row = jTableData.getSelectedRow();
String name = (String) model.getValueAt(no_row,1);
String loc = (String) model.getValueAt(no_row,2);
id=Integer.parseInt(model.getValueAt(no_row,0).toString());
EditName.setText(name);
EditLocation.setText(loc);
}
private void jButtonDeleteActionPerformed(java.awt.event.ActionEvent evt) {
try {
int no_row = jTableData.getSelectedRow();
int id = Integer.parseInt(jTableData.getValueAt(no_row,0).toString());
String query ="DELETE FROM data WHERE id =?";
PreparedStatement prst=con.prepareStatement(query);
prst.setInt(1,id);
prst.executeUpdate();
System.out.println("Deletion Completed");
prst.close();
} catch (SQLException ex) {
Logger.getLogger(DataJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
jButtonClearAll.doClick();
jButtonRefresh.doClick();
}
private void jButtonUpdateActionPerformed(java.awt.event.ActionEvent evt) {
try {
PreparedStatement prst = con.prepareStatement("UPDATE data SET name=?, location=? WHERE id = ?");
String name= EditName.getText();
String loc = EditLocation.getText();
prst.setString(1,name);
prst.setString(2,loc);
prst.setInt(3, id);
prst.executeUpdate();
System.out.println("Update Completed!");
prst.close();
} catch (SQLException ex) {
Logger.getLogger(DataJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
jButtonClearAll.doClick();
jButtonRefresh.doClick();
}
private void jButtonClearAllActionPerformed(java.awt.event.ActionEvent evt) {
EditName.setText(null);
EditLocation.setText(null);
jTextFieldName.setText(null);
jTextFieldLocation.setText(null);
DefaultTableModel model = (DefaultTableModel) jTableData.getModel();
model.setRowCount(0);
}
public static void main(String args[]) {
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(DataJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DataJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DataJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DataJFrame.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() {
new DataJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField EditLocation;
private javax.swing.JTextField EditName;
private javax.swing.JButton jButtonClearAll;
private javax.swing.JButton jButtonDelete;
private javax.swing.JButton jButtonEdit;
private javax.swing.JButton jButtonInsert;
private javax.swing.JButton jButtonRefresh;
private javax.swing.JButton jButtonUpdate;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTableData;
private javax.swing.JTextField jTextFieldLocation;
private javax.swing.JTextField jTextFieldName;
// End of variables declaration
}
Note: If you directly copy from this code to your java applicaion, pls consider your package name and class name of your application.
Ohhh!brilliant work !
ReplyDeletenice work
ReplyDeletesemaya ji
ReplyDeleteThank you. keep your support.
ReplyDelete