我使用以下方法从dob中计算年龄和当前日期在java中,dob存储在数据库表中,使用getter setter方法导出dob值并将dob传递给getAge1方法,在方法查询中运行良好的php myadmin mysql控制台,当我在查询结果集中存储查询结果时,它在int age变量中给出null值。
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;
}
答案 0 :(得分:0)
试试这个:
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 强>
<强>更新:1 强>
String s3 = "SELECT TIMESTAMPDIFF(YEAR,"+ dob +",CURDATE()) from custregister where cid='+id'" ;
答案 1 :(得分:0)
在传递给SELECT语句的日期值周围添加单个引号。