简体   繁体   中英

To calculate age from dob and current date in java

I am using following method to calculate age from dob and current date in java,dob is stored in database table,using getter setter methods dob value is derived and passing dob to getAge1 method,in method query runs fine in php myadmin mysql console,when i am storing query's result in resultset its giving null value here in int age variable.

public int getAge1(int id,String dob)
{


    try { 
        System.out.println("DOB is:"+dob);
        System.out.println("Id is:"+id);
         Connection conn = null;
         conn = DbConnection.getConnection();
         PreparedStatement ps = null;
         ResultSet rs = null;   

         String s3 = "SELECT TIMESTAMPDIFF(YEAR,"+ dob +",CURDATE()) from custregister where cid="+ id ;

         System.out.println("sql :"+s3);
            ps = conn.prepareStatement(s3);
            rs = ps.executeQuery();
            while (rs.next()) 
            {

                int s2 =rs.getInt(1);
                System.out.println("Age is "+s2);
                age=s2;
            }
    }catch(Exception e){e.printStackTrace();}   
    //SELECT TIMESTAMPDIFF(YEAR, 'dob', CURDATE()) AS age;
    return age;
}   

try this:

     SELECT 
     TIMESTAMPDIFF(YEAR, dob, CURDATE())AS AGE 
     from custregister 
     where cid= your id ;

http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_timestampdiff

update:1

String s3 = "SELECT TIMESTAMPDIFF(YEAR,"+ dob +",CURDATE()) from custregister  where cid='+id'" ;

在传递给该SELECT语句的日期值周围添加单引号。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM