JDBC Desktop Application
Clear Button Coding
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setText(" ");
jTextField2.setText(" ");
jTextField3.setText(" ");
jTextField4.setText(" ");
}
Create a Table :
create table hostellers(id varchar(100), name varchar(100), block varchar(100), roomnumber varchar(100))
JButton2 Coding
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try{
// Loading Driver
Class.forName("com.mysql.cj.jdbc.Driver");
//Creating Connection
Connection con =DriverManager.getConnection("jdbc:mysql://172.16.100.8/rkmishradb","rkmishra","a");
// Create Statement
Statement stmt =con.createStatement();
// Storing Values to String avraible
String id=jTextField1.getText();
String name=jTextField2.getText();
String block =jTextField3.getText();
String room =jTextField4.getText();
// Execute Query
stmt.executeUpdate("insert into hostellers values('"+id+"','"+name+"','"+block+"','"+room+"' )");
JOptionPane.showMessageDialog(null, "Data Successfully Saved");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "Something Wrong" + e);
}
}
JButton3 for Update
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try{
// Loading Driver
Class.forName("com.mysql.cj.jdbc.Driver");
//Creating Connection
Connection con =DriverManager.getConnection("jdbc:mysql://172.16.100.8/rkmishradb","rkmishra","a");
// Create Statement
Statement stmt =con.createStatement();
// Storing Values to String avraible
String id=jTextField1.getText();
String name=jTextField2.getText();
String block =jTextField3.getText();
String room =jTextField4.getText();
// Execute Query
stmt.executeUpdate("update hostellers set name='"+name+"',block='"+block+"', roomnumber='"+room+"'");
JOptionPane.showMessageDialog(null, "Data Successfully Updated");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "Something Wrong" + e);
}
}
JButton4 Display
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
try{
// Loading Driver
Class.forName("com.mysql.jdbc.Driver");
//Creating Connection
Connection con=DriverManager.getConnection("jdbc:mysql://172.16.100.8/rkmishradb","rkmishra","a");
// Create Statement
Statement stmt =con.createStatement();
// Execute Query
ResultSet rs= null;
rs=stmt.executeQuery("select *from hostellers");
DefaultTableModel tm=(DefaultTableModel)jTable1.getModel();
tm.setRowCount(0);
while(rs.next())
{
Object o[]={rs.getString(1),rs.getString(2),rs.getString(3), rs.getString(4)};
tm.addRow(o);
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "Something Wrong" + e);
}
}