我想将 5 条数据插入到一个 SQL 表中,其中最后 4 条数据已经工作正常,但第一个数据应该来自另一个表(一个 String),为我插入它的表提供一个 Int 值。到目前为止,这是我的解决方案。但是我仍然收到错误: “索引 5 超出范围。”
PreparedStatement stmt = connection.prepareStatement("INSERT INTO RECORDS (LocationId, RecId, RecValues, YearTime, HourTime) VALUES " +
"((SELECT LocationId from Locations where Location_name = 'Mic HR1'), ?, ?, ?, ?)");
stmt.setInt(1,1);
stmt.setInt(2, recid);
stmt.setInt(3, inputData);
stmt.setDate(4, sqlDate);
stmt.setTime(5, Time.valueOf(dtf.format(now)));
stmt.executeUpdate();
最佳答案
实际上,您在查询中只定义了四个参数,因为 LocationId 是由您提供的内部选择计算的。这就是您收到错误的原因。
试试这个:
PreparedStatement stmt = connection.prepareStatement("INSERT INTO RECORDS (LocationId, RecId, RecValues, YearTime, HourTime) VALUES " +
"((SELECT LocationId from Locations where Location_name = 'Mic HR1'), ?, ?, ?, ?)");
stmt.setInt(1, recid);
stmt.setInt(2, inputData);
stmt.setDate(3, sqlDate);
stmt.setTime(4, Time.valueOf(dtf.format(now)));
stmt.executeUpdate();
关于Java MS SQL 在插入中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55243377/