我想在另一个表中使用带有select子查询的insert语句。就我而言,我想在PRESENTATION
表到AVAILABILITY
表中添加一行。
AVAILABILITY
表格结构:
availableID (number, generated using sequence)
availableDay (varchar)
availableStart (varchar)
availableEnd (varchar)
lecturerID(FK) (varchar)
presentationID(FK) (number, generated using sequence)
PRESENTATION
表格结构:
presentationID (number, generated using sequence)
presentationDay (varchar)
presentationStart (varchar)
presentationEnd (varchar)
我尝试在DAO中构建查询,如下所示:
String lecturerID = Abean.getLecturerID();
String availableDay = Abean.getAvailableDay();
String availableStart = Abean.getAvailableStart();
String availableEnd = Abean.getAvailableEnd();
Date availableDate = Abean.getAvailableDate();
String presentationID = Abean.getPresentationID();
try{
currentCon = JavaConnectionDB.getConnection();
PreparedStatement ps=currentCon.prepareStatement("
insert into availability (availableID,
lecturerID,
availableDay,
availableStart,
availableEnd,
presentationid)
select(availabilityseq.nextval,
?,
presentationDay,
presentationStart,
presentationEnd,
presentationid)
from presentation where presentationid=?
");
ps.setString(1,Abean.getLecturerID());
ps.setString(2,Abean.getAvailableDay());
ps.setString(3,Abean.getAvailableStart());
ps.setString(4,Abean.getAvailableEnd());
ps.setString(5,Abean.getPresentationID());
// ps.setString(6,Abean.getAvailableID());
ps.executeUpdate();
}
catch(Exception e){
System.out.println("add availability 2 failed: An Exception has occurred! " + e);
}
正如所料,它返回错误
错误:java.sql.SQLException: Invalid column index
那么,如何使用额外的列插入子查询?
更新:MY DAO代码
答案 0 :(得分:0)
您需要将绑定变量值的设置与SQL文本中的绑定变量规范相匹配:
编辑4月18日:从select子查询中删除了括号
PreparedStatement ps=currentCon.prepareStatement("
insert into availability (availableID,
lecturerID,
availableDay,
availableStart,
availableEnd,
presentationid)
select availabilityseq.nextval,
?,
presentationDay,
presentationStart,
presentationEnd,
presentationid
from presentation where presentationid=?
");
ps.setString(1,Abean.getLecturerID()); // match first "?"
ps.setString(2,Abean.getPresentationID()); // match 2nd "?"