How To Display Data From MySQL in Java Using NetBeans 12

  1. Cick File, New Project, Java Application, and give it a project name: JtableDB.

2. Click Jtabledb under Surce Packages, New, JFrame Form and change class name: JtableData.

3. Click onJtableData.java (form) and click on Design.  Add a Button and a Table.

4/ Click on table (jTable1), right-click to open pop-up menu, and click on Properties, then Click on model.

5. Modify table so Column titles are id, username, and password.

6.The database being used contains the following table and data.

7. Right click on the button, events, action, action performed.

8. In the JtableData.java, go to source code, and add “import java.sql.*”.

9. In the button’s Action event, add the following:

//database connection
try {
    //open database connection
    Class.forName(“com.mysql.jdbc.Driver”);
         Connection con = DriverManager.getConnection(“jdbc:mysql://localhost:3306/mydb?useSSL=false”,”root”,”mysql@123”);
         Statement st = con.createStatement();


    //mysql query      
    String sql = “select * from login”;
    ResultSet rs = st.executeQuery(sql);


    while(rs.next()){
        //each record from db table will be read and data stored in string variables
        String id = String.valueOf(rs.getint(“id”));
        String username = rs.getString(“username”);
        String password = rs.getString(“password”);

        //create string array to store data retrieved from db table
        String tbData[] = {id,username,password};
        DefaultTableModel tblModel = (DefaultTableModel)jTable1.getModel();

        //add string array data into jtable
        tblModel.addRows(tbData);
                  }
con.close();

   } catch(Exception e) {
            System.out.println(e.getMessage()); }

Leave a Reply

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