Java And MySQL Execute COUNT, MAX MIN, AVG

How To Execute MySQL Database Count Max  Min Avg In Java NetBeans

get database count,minimum,maximum,average using java



In this Java Tutorial we will see How To:
 - execute count command to get database table records count.
 - execute min command to get database minimum value.
 - execute max command to get database maximum value.
 - execute avg command to get database average value.
In Java Programming Language Using NetBeans Editor And MySQL Database.




Project Source Code:

 // create a function to connect with mysql database
    public static Connection getConnection()
    {
        Connection con = null;
        
         try {

            Class.forName("com.mysql.jdbc.Driver");
             con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
        } catch (Exception ex) {

             System.out.println(ex.getMessage());

        }
        return con;
    }
    

// create a function to execute the query
public void execQuery(String query){
        
       try{
           
           Connection con = getConnection();
           Statement st = con.createStatement();
           ResultSet rs = st.executeQuery(query);
           
           if(rs.next()){
               jTextField1.setText(Integer.toString(rs.getInt(1)));
           }else
               System.out.println("No Data Found");
           
       }catch(Exception e){
           
       }
    }
    
// COUNT
private void jButtonCOUNTActionPerformed(java.awt.event.ActionEvent evt) {                                             
        String query = "SELECT COUNT(*) FROM dgv_data";
        execQuery(query);
    }                                            

// MINIMUM
    private void jButtonMAXActionPerformed(java.awt.event.ActionEvent evt) {                                           
        String query = "SELECT MAX(age) FROM dgv_data";
        execQuery(query);
    }                                          

// MAXIMUM
    private void jButtonMINActionPerformed(java.awt.event.ActionEvent evt) {                                           
        String query = "SELECT MIN(age) FROM dgv_data";
        execQuery(query);
    }                                          

// AVERAGE
    private void jButtonAVGActionPerformed(java.awt.event.ActionEvent evt) {                                           
        String query = "SELECT AVG(age) FROM dgv_data";
        execQuery(query);
    }

OutPut:

get mysql table count,max,min,avg using java



Share this

Related Posts

Previous
Next Post »