【发布时间】:2015-01-30 06:03:53
【问题描述】:
我在java中创建了两个方法,一个返回数据库服务器时间,另一个返回数据库服务器一小时前的时间。现在我必须将这两个日期时间用于sql查询。检索数据库的代码服务器时间是:-
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;
}
另一种检索一小时前时间的方法是
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;
}
但是当我在 sql 查询中使用 stringDate 和 timestr 时,我得到一个错误 com.microsoft.sqlserver.jdbc.SQLServerException: Conversion failed when converting date and/or time from character string.
sql查询的代码是:-
String sql = "select * from vs1_bag where logtime between 'stringDate'and 'timestr' ";
编辑:- 我将检索时间并在我的应用程序中使用它的方法是:-
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;
}
如何解决。
【问题讨论】:
-
日志时间列是日期时间列吗?并使用 Prepare 语句
-
yes logtime 是 datetime 类型的。
-
如果我没记错的话,您会在“日期日期 = simpleDateFormat.parse(timestr);”处收到错误消息。我检查了 SqlServer,它在执行“select GETDATE()”时给出了“2014-12-02 09:56:46.870”。删除“.870”表示最后微秒部分后尝试测试。
-
你的sql查询错误。查看答案并尝试一下。告诉我它是否有效
标签: java sql-server datetime