目前我正在尝试将时间戳值插入 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.info(timestampcurrent + "\"+ timestampcurrent.toString());
信息 [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());
信息 [http-8080-2] (ecsystem.java:233) - 2013-11-22 15:34:55.0\2013-11-22 15:34:55.0
希望所有这些信息有帮助!
最佳答案
您永远不应该使用字符串连接来向查询添加动态参数,原因如下:
- 用于日期、时间等的格式因数据库而异,甚至区域设置也不同。并且 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);
关于Java 日历/日期转 SQL 时间戳/Oracle 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20100751/