Categories
Class 12

Connect MySQL Database Employee in Netbeans

Write Java code to connect to a MySQL database namely Employee and then fetch all records from table Employee where salary is greater than Rs. 7000.

import java.sql.*;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){                                         
    DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
    int rows = model.getRowCount();
    if(rows > 0){
        for(int i = 0; i < rows; i++){
            model.removeRow(0);
            try{
                Class.forName("java.sql.Driver");
                Connection con = DriverManager.getConnection("jdbc:mysql://localhost/office", "root", "secret");
                Statement stmt = con.createStatement();
                String sfld = jTextField1.getText();
                String query = "select empid, name, salary from Employee where salary" + sfld + ";";
                ResultSet rs = stmt.executeQuery(query);
                while(rs.next()){
                    model.addRow(new Object[]{rs.getInt(1), rs.getString(2), rs.getDouble(3)});
                }
                rs.close();
                stmt.close();
                con.close();
            }catch(Exception e){
                JOptionPane.showMessageDialog(null, e);
            }
        }
    }
}

Leave a Reply