I have created two methods in java ,one of which returns the database server time and other returns the one hour ago time of database server.Now I have to use these two date time into a sql query.The code for retrieving database server time is:-
public String database_Time() throws SQLException
{
con = getConnection();
String sql = "select GETDATE()";
clstmt = con.prepareCall(sql);
clstmt.execute();
rs = clstmt.getResultSet();
while(rs.next()) {
timestr= rs.getString(1);
}
System.out.println("database time is" +timestr);
return timestr;
}
Another method for retrieving one hour ago time is
public String previostime() throws ParseException, SQLException
{
database_Time();
String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
Date date = simpleDateFormat.parse(timestr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
hours--;
calendar.set(Calendar.HOUR_OF_DAY, hours);
fixedDate = calendar.getTime();
stringDate = simpleDateFormat.format(fixedDate );
System.out.println("previous date is"+(stringDate));
System.out.println("current date is"+timestr);
return stringDate;
}
But when I use stringDate and timestr in sql query ,then I got an error that com.microsoft.sqlserver.jdbc.SQLServerException: Conversion failed when converting date and/or time from character string.
Code for sql query is:- String sql = "select * from vs1_bag where logtime between 'stringDate'and 'timestr' ";
Edit:- Method through which I will retrieve the time,and will use it in my application is:-
public String [] getChartTime() throws SQLException, ParseException
{
List<String> tStr = new ArrayList<String>();
database_Time();
String atime[] = null;
previostime();
getConnection();
try
{
con = getConnection();
stmt = con.createStatement();
String sql = "select * from vs1_bag where logtime between 'stringDate'and 'timestr' ";
stmt.executeQuery(sql);
rs = stmt.getResultSet();
while(rs.next()) {
// Just get the value of the column, and add it to the list
tStr.add(rs.getString(1).substring(11,16));
}
}
catch( Exception e )
{
System.out.println("\nException in Bean in getDbTable(String code):"+e);
}
finally
{
closeConnection();
}
// I would return the list here, but let's convert it to an array
atime= tStr.toArray(new String[tStr.size()]);
return atime;
}
How to resolve it.
shouldn't it be like this? :
String sql = "select * from vs1_bag where logtime between '"+stringDate+"' and '"+timestr+"' ";
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.