如何在 Java 中将变量值作为一种方法传递到另一种方法作为数据库查询的参数



我已经从数据库中检索了logtime的值,并从检索到的logtime中计算了一小时前的时间。检索logtime的代码是

public String database_Time() {
  try {
    con = getConnection();
    String sql = "select max(logtime) from vacuum_analog_1mins";
    clstmt = con.prepareCall(sql);
    clstmt.execute();
    rs = clstmt.getResultSet();
    while (rs.next()) {
      timestr = rs.getString(1);
    }
  } catch (Exception e) {
    System.out.println("nException in  Bean in getDbTable(String code):" + e);
  } finally {
    closeConnection();
  }
  return timestr;
}

计算一小时前时间的代码是:

public Date previostime() throws ParseException
{
  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);
  Date fixedDate = calendar.getTime();
  System.out.println("previous date is" + (fixedDate));
  System.out.println("current date is" + timestr);
  return fixedDate;
}

现在我想在我的另一个方法中使用这两个变量 fixedDate 和 timestr,其中这些变量将用作 sqlquery 的参数,如下所示:

List < String > timeStr = new ArrayList < String > ();
database_Time();
String atime[] = null;
database_Time();
previostime();
getConnection();
try {
  con = getConnection();
  String sql = "exec vcs_gauge @gauge_name=?,@first_rec_time=?,@last_rec_time=?";
 
  clstmt = con.prepareCall(sql);
  clstmt.setString(1, "vs1_bag");
  clstmt.setString(2, "fixedDate");
  clstmt.setString(3, "timestr");
  clstmt.execute();
  rs = clstmt.getResultSet();
  while (rs.next()) {
    // Just get the value of the column, and add it to the list
    timeStr.add(rs.getString(1).substring(11, 16));
  }

但没有结果。请帮助我哪里出错了。我也将这些变量声明为全局变量。

这两行不正确

clstmt.setString(2, "fixedDate");
clstmt.setString(3, "timestr");

如果在 sql 中它们是日期类型,请尝试以下操作:

clstmt.setDate(2, java.sql.Date(fixedDate.getTime()));
clstmt.setDate(3, java.sql.Date.valueOf(timestr));

最新更新