how to get DB server current time?
i know we can get that info via calling a server function like now() in MySQL or getDate() in MsSQL.
since the function name can be different between servers, we can not depend on that to build (database) portable application. so with java api which support cross platform (cross environtment), can we obtain that info? (con.getServerTime()?)
# 1
well if you need the current time of the db i don't think there is a direct solution(Platform Independent Solution) for it.
However we can use can get a list of Time & Date specific functions which a target database supports and the name of the database.
try{
DatabaseMetaData dbmd = con.getMetaData();
String dbProductName = dbmd.getDatabaseProductName();
String DbSupportedTimeDateFunctions = dbmd.getTimeDateFunctions()
ArrayList<String> dateTimeFuncList = new ArrayList<String>();
StringTokenizer st = new StringTokenizer( DbSupportedTimeDateFunctions,",");
while(st.hasMoreElements())
dateTimeFuncList.add(st.nextElement());
}catch(SQLException sqe){
sqe.printStackTrace();
}
and now depending on both of the option you may go ahead use one of them to acheive what you want.
it might be a hardcoded solution but caush we might have to by the way it is.
# 2
You could always revisit the requirement/design that leads to that need.
# 3
thanks RahulSharna. but dbmd.getTimeDateFunctions returns a list & i can't distinguish which one i need. also with jtds jdbc driver which support 2 kind server (mssql & sybase), the list are not valid function.
my solution now is make my jdbc-dao class has abstract method getServerCurrentTime or getServerCurrentTimeFunction.
so subclass of jdbc-dao like mysql-dao and mssql-dao just need to implement that method.
# 4
not a good solution... i still need to code implementation on each dao class. now i'm seperating server function in a interface and put in dao constructor.
// ServerFunction.java
public interface ServerFunction {
String getNow();
}
// JdbcDao.java
public class JdbcXXXDao implements XXXDao {
public JdbcXXXDao(DataSource ds, ServerFunction sf) {
this.ds = ds;
this.sf = sf;
}
}
// in DAOFactory
public XXXDao getXXXDao(int servertype) {
XXXDao result = null;
ServerFunction sf = null;
switch (servertype) {
case MS_SQL :
sf = new ServerFunction() {
public String getNow() { return "getDate()"; }
};
break;
case MY_SQL :
sf = new ServerFunction() {
public String getNow() { return "now()"; }
};
break;
case ORACLE :
sf = new ServerFunction() {
public String getNow() { return "SYSTIME"; }
};
break;
}
result = new JdbcXXDao(ds, sf);
return result;
}
please suggest me if you have any better solution. Thank you.
# 5
Use the JDBC escaped function call :
// for Oracle2
String sql =
"select {fn now()}from dual" ;
ResultSet rs = stmt.executeQuery(sql);
while (rs.next())
System.out.println("result: " + rs.getString(1) + rs.getString(1) );
Most other DB
String sql = "select {fn now()}" ;
http://www.rgagnon.com/javadetails/java-0383.html