Java日历/日期到SQL时间戳/ Oracle数据库

时间:2013-11-20 15:59:29

标签: java sql oracle

目前我正在尝试将时间戳值插入Oracle数据库时间戳字段。

使用CURRENT_TIMESTAMP我可以将数据插入数据库

它返回的时间戳是( 2013-11-20.14.50.7.832000000

所以我解释这个问题。我需要一个创建的日期/时间(时间戳)和一个过期的日期/时间(时间戳)。所以我使用Java日历来处理额外的日子。例如,添加365天以获得一年到期。

这是我当前的Java日期代码:

    public Date GetCurrentDate(HttpServletRequest request, HttpServletResponse response) throws Exception{

    //Create current Date
    Calendar cal = new GregorianCalendar();
    Date creationDate = cal.getTime();



    return creationDate;


}

     Date datereturn = GetCurrentDate(request,response);
         java.sql.Timestamp timestampcurrent = new Timestamp(datereturn.getTime()); 
         timestampcurrent.setNanos(0);

以下是为当前日期添加2小时以生成到期日期并将其添加到时间戳的代码。

//Set Expired Date/Time Based from xml Evaluation (Days)
            Calendar cal = Calendar.getInstance();
            cal.setTime(datereturn);
            cal.add(Calendar.DAY_OF_YEAR,Integer.parseInt(getServletContext().getInitParameter("EXPIRED_DAYS_EVALUATION"))); // this will add two hours
            expireddatereturn = cal.getTime();
            timestampexpired = new Timestamp(expireddatereturn.getTime());
            timestampexpired.setNanos(0);
            logText.info(timestampexpired   + "    " + timestampcurrent .toString());

所以我现在有两个时间戳,“ timestampcurrent ”(当前日期)和“ timestampexpired ”(到期日期)。

我正在尝试将这些值插入到oracle数据库中,但我收到错误:

                String sqlInsertData ="INSERT INTO EC_TABLE" +
                    "(licenseid, customername, description, servername,licensetype, username,password, createdDateTime,ExpiredDateTime)" +
                    " VALUES ('"+LicenseID+"','"+CustomerName+"','"+Description+"','"+ServerName+"','"+LicenseType+"','"+EncryptedUsername+"','"+EncryptedPassword+"','"+timestampcurrent+"','"+timestampexpired+"')";

错误是:ORA-01843:不是有效月份

试图解决这个问题几个小时但我找不到问题!请帮忙!

其他信息:

logText返回:

logText.info(timestampcurrent +“\”+ timestampcurrent.toString());

INFO [http-8080-2](ecsystem.java:233) - 2013-11-20 15:34:55.0 \ 2013-11-20 15:34:55.0

logText.info(timestampexpired +“\”+ timestampexpired.toString());

INFO [http-8080-2](ecsystem.java:233) - 2013-11-22 15:34:55.0 \ 2013-11-22 15:34:55.0

希望所有这些信息都有帮助!

2 个答案:

答案 0 :(得分:2)

出于以下原因,您永远不应该使用字符串连接来向查询添加动态参数:

  • 用于日期,时间等的格式因数据库而异,甚至将语言环境结束到语言环境。并且Java类型的toString()表示不一定与数据库期望的那些匹配
  • 只要您在字符串中有单引号或换行符,查询就会变为无效
  • 某些类型(如字节数组等)没有任何字符串表示
  • 这会将您的应用程序打开到SQL injection attacks

因此,您应该使用prepared statements

String sql =
    "INSERT INTO EC_TABLE" +
    "(licenseid, customername, description, servername,licensetype, username,password, createdDateTime,ExpiredDateTime)" +
    " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, licenseId);
...
stmt.setTimestamp(9, timestampexpired);

答案 1 :(得分:0)

插入时可以使用以下内容

to_date('"+timestampcurrent+"', 'YYYY-DD-MM HH:MI:SS')

同样对于timestampexpired,这应该可以解决这个问题。