Home Tutorial Java Jdbc Mysql JDBC Select Max Example

 
 

JDBC Select Max Example
Posted on: October 15, 2010 at 12:00 AM
Advertisement
In this tutorial we will learn how use MAX ()  in query with mysql JDBC driver.

JDBC Select Max Example

In this tutorial we will learn how use  MAX ()  in query with mysql JDBC driver. This  tutorial  use the MAX  mysql  function that fetch the maximum value of column values   that  pass in Max function  i.e  "SELECT MAX(user_id) FROM user" . Table user as:

 

    Mysql query "SELECT MAX(user_id) FROM user"  fetch the  maximum user_id  is 5 and if insert another row data  in table user then increase user_id  so  query  fetch  result   maximum  user_id  6. This type  query use if need max salary , max user_id etc. The code  of  "SelectMax.java" as:

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.SQLException;
import java.sql.ResultSet;
  
public class SelectMax{
 // JDBC driver name and database URL
 static String driverName = "com.mysql.jdbc.Driver";
 static String url = "jdbc:mysql://localhost:3306/";

 // defined and set value in  dbName, userName and password variables
 static String dbName = "testjdbc";
 static String userName = "root";
 static String password = "";
	
 public static void main(String[] args){
	// create Connection con, and Statement stmt 
	Connection con=null;
	Statement stmt=null;
	try{
		Class.forName(driverName).newInstance();
		con = DriverManager.getConnection(url+dbName, userName, password);
		try{
			stmt = con.createStatement();
			String query = "SELECT MAX(user_id) FROM user";
			ResultSet rs=stmt.executeQuery(query);			
			//Extact result from ResultSet rs
			while(rs.next()){
			    System.out.println("MAX(user_id)="+rs.getInt("MAX(user_id)"));				
			  }
			// close ResultSet rs
			rs.close();
		   } catch(SQLException s){						
				s.printStackTrace();
			 }
		// close Connection and Statement
		con.close();
		stmt.close();
		}catch (Exception e){
			e.printStackTrace();
		 }
  }
}

Program Output  :

F:\jdbc>javac SelectMax.java

F:\jdbc>java SelectMax
MAX(user_id)=5

F:\jdbc>

Download Code

Advertisement

Related Tags for JDBC Select Max Example:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 15, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com