使用`COALESCE`在`prepareStatement`中用于“insert into”命令。

huangapple go评论61阅读模式
英文:

Use COALESCE in prepareStatement for "insert into" cmd

问题

我正在尝试执行以下命令,但是这个命令抛出了异常:

> org.hsqldb.HsqlException:操作中的数据类型不兼容

conn.prepareStatement("INSERT INTO TableA (colA) VALUES (IFNULL(?, 1))")

这里的TableA具有整数数据类型的colA。
然而,如果我将上述命令更改为

conn.prepareStatement("INSERT INTO TableA (colA) VALUES(IFNULL(null, 1))")

可以正常工作,但没有任何意义,因为想在运行时传递colA的值。

代码:

ps = conn.prepareStatement("INSERT INTO TableA (colA) VALUES(IFNULL(?, 1))")

ps.setObject(1, 5); // 这个命令没有任何问题,代码在preparestatement阶段失败

英文:

I am trying to execute below cmd but this one is throwing an exception:

> org.hsqldb.HsqlException: incompatible data type in operation

conn.prepareStatement("INSERT INTO TableA (colA) VALUES (IFNULL(?, 1)))

Here TableA has colA with integer datatype.
However, if I change above cmd to

conn.prepareStatement("INSERT INTO TableA (colA) VALUES(IFNULL(null, 1)))

works properly but doesn't make any sense because want to pass colA value at runtime.

code:

   ps = conn.prepareStatement("INSERT INTO TableA (colA) VALUES(IFNULL(?, 1))")

   ps.setObject(1, 5);  // this cmd doesn't have any problem code is failing at preparestatement itself

答案1

得分: 1

setObject 是一个通用的方法,因此如果你想要强制使用某种类型,可以按照以下方式使用第三个参数:

ps.setObject(1, 5, JDBCType.INTEGER);

因为你使用了一个常量值,所以编译器必须决定它是整数还是其他数值类型。

你也可以这样写:

Integer myValue = 5;
ps.setObject(1, myValue);

或者

Integer myValue = 5;
ps.setObject(1, myValue.intValue());
英文:

setObject is generic so if you want to force to use a type you can use the third parameter as follow:

ps.setObject(1, 5, JDBCType.INTEGER);

Because you have used a constant value, so your compiler must decide if is an integer or another numeric type.

You can write also

Integer myValue = 5;
ps.setObject(1, myValue);

or

Integer myValue = 5;
ps.setObject(1, myValue.intValue());

答案2

得分: 0

使用 setInt 替代 setObject

ps.setInt(1, 5);
英文:

Use setInt instead of setObject

ps.setInt(1, 5);

huangapple
  • 本文由 发表于 2020年5月4日 21:22:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/61593259.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定