简体   繁体   English

如何在JDBC PreparedStatement中设置公式

[英]How to set a formula in a JDBC PreparedStatement

I have a PreparedStatement that I use to insert a bunch of rows with a lot of column data. 我有一个PreparedStatement,我用它来插入一堆包含大量列数据的行。 However, for one of the columns (a Timestamp), if the value is null, I want it to execute getDate() on the server. 但是,对于其中一个列(时间戳),如果值为null,我希望它在服务器上执行getDate()

I understand that I could just do new Date() but that's not really going to work, because, due to legacy reports, it needs to match exactly another column that has the value automatically inserted. 我知道我可以做new Date()但这不会真正起作用,因为,由于遗留报告,它需要匹配另一个具有自动插入值的列。

Let's also say I can't change the schema and add a default value to the column. 我们还说我无法更改架构并为列添加默认值。

Is there any way I can set a formula as a parameter in the PreparedStatement? 有没有办法可以在PreparedStatement中将公式设置为参数?

Edit to Add: Here's essentially what it is currently: 编辑添加:这里基本上是它当前的内容:

PreparedStatement statement = connection.prepareStatement("insert into row (name, starttime) values (?, ?)")
statement.setString(1, name);
statement.setDate(2, date);

What I want is, something like: 我想要的是,像:

PreparedStatement statement = connection.prepareStatement("insert into row (name, starttime) values (?, ?)")
statement.setString(1, name);
if(date != null)
  statement.setDate(2, date);
else
  statement.setFormula(2, "getdate()");

I understand that: 我明白那个:

if(date == null)
  date = new Date();

is essentially the same thing, but in our case, it's really not. 基本上是相同的,但在我们的情况下,它真的不是。

Does it work to simply prepare a statement of the form 简单地准备表单声明是否有效

insert into row(name, starttime)
   values(?, coalesce(?, getdate())

? and then setting a null 2nd parameter should cause a getdate() call? 然后设置null第二个参数应该导致getdate()调用?

The only option I can think of, since you cannot change the schema, is to have 2 prepared statements, one with the default getdate() in the query, the other that takes a parameter. 我能想到的唯一选择,因为你无法改变模式,就是有2个预准备语句,一个在查询中使用默认的getdate(),另一个在参数中使用。 Then you can simply do something like: 然后你可以简单地做一些事情:

PreparedStatement ps = (date == null) ? prepareWithDefault : prepareWithoutDefault;

// Set all variables //

if (date != null) {
  ps.setDate(date);
}

ps.execute();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM