在插入查询中为PreparedStatement选择子查询

时间:2019-01-28 18:30:19

标签: java mysql jdbc

我想将SELECT子查询用作PreparedStatement插入INSERT查询... 我正在尝试使用自定义值填充2列,并使用子查询填充第三列...

query = "insert into invoiceOrders (productCode,quantity,amount) values (?,?,select price from priceTable where proCode=pCode)";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(0,"productCode");
stmt.setString(1,"qty");
/*3rd column will be filled be subquery*/
n = stmt.executeUpdate();

1 个答案:

答案 0 :(得分:1)

子查询:

select price from priceTable where proCode=pCode

必须用括号括起来,并确保仅返回1行
另外,参数pCode是什么?
我认为您应该将其替换为?,然后再将其值传递给setString()
setString()方法的第一个参数也是基于1的。
因此更改为:

query = "insert into invoiceOrders (productCode,quantity,amount) values (?,?,(select price from priceTable where proCode=?))";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1,"productCode");
stmt.setString(2,"qty");
stmt.setString(3,pCode);  // or stmt.setInt(3,pCode);
n = stmt.executeUpdate();