Java Database Connectivity : Searching Data

How to search for data on a database through Java GUI. We will be using a list to search for data in a table according to its primary key and showing its details on the text-fields.

JDBC

Steps:-

1 Follow the 1-5 steps of Viewing Data in GUI.
2 In the design view,insert text-fields according to your database to show the details and a search button.
3 Insert a list swing control.Now do as directed to create a new list model – Right click on list » properties » click on the ellipsis button of model property » select Custom Code from the drop down menu » write new DefaultListModel () in the given space.
4 Under your package and before class starts write the following codes in the source tab.

  import java.sql.*;

 import javax.swing.JOptionPane;
 import javax.swing.DefaultListModel;
5 Write the coding on the button’s actionPerformed event for the connectivity and for populating the data in the list.
DefaultListModel list=(DefaultListModel) jList1.getModel();
    String sql=”Select * from library”;
    try {
        Class.forName(“com.mysql.jdbc.Driver”);
        Connection con= (Connection) DriverManager.getConnection(“jdbc:mysql://localhost:3306/database1“,”root”,””);
        Statement stmt=con.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        while(rs.next()){
            String no=rs.getString(“no”);
            list.addElement(no);
        }
        jList1.setModel(list);
    }
    catch(Exception e) {
        JOptionPane.showMessageDialog(this, e.getMessage());
    }
6 Now write these codes on the list’s mouseClicked event for making the data appear on text-fields when we select a row in the list.

try {
        Class.forName(“com.mysql.jdbc.Driver”);
        Connection con= (Connection) DriverManager.getConnection(“jdbc:mysql://localhost:3306/database1“,”root”,””);
        Statement stmt=con.createStatement();
        String num  = (String) jList1.getSelectedValue();
        String sql1 = “Select * from library where no = ‘” + (num) + “‘”;
        ResultSet rs = stmt.executeQuery(sql1);
            while (rs.next())
        {
            String no = rs.getString(“NO”);
            String title= rs.getString(“TITLE”);
            String auth= rs.getString(“AUTHOR”);
            jTextField1.setText(“”+no);
            jTextField2.setText(“”+title);
            jTextField3.setText(“”+auth);
        }
    }
    catch(Exception e) {
        JOptionPane.showMessageDialog(this, e.getMessage());
    }

7 Change the codes in blue according to your database. Finally, run the file(Shift +F6)

Run View

Add some labels and uncheck the editable property of text-fields to make the design look better.
After searching the data, you can allow users to update or delete rows.
// watch a video tutorial for java database connectivity on the videos page

Leave a Comment

Your email address will not be published. Required fields are marked *