我的做法是先创建一个临时表,将需要插入的数据先插入到临时表里面,然后把这个临时表作为参数,传送给stored procedure。使用了Preparestatement来避免SQL注入问题。
先创建User Defined Table
CREATE TYPE UserIdList AS TABLE(
userId uniqueidentifier NOT NULL
);
再创建存储过程:
CREATE PROC insertIntoExamArrange
@subjectId uniqueidentifier,
@startTime datetime2(0),
@duration time(7),
@site nvarchar(255),
@examName nvarchar(255),
@studentIdList dbo.UserIdList READONLY,
@supervisorIdList dbo.UserIdList READONLY
AS
BEGIN
DECLARE @op TABLE (
colGuid uniqueidentifier
);
DECLARE @examId uniqueidentifier;
BEGIN TRAN
INSERT INTO dbo.ExamArrange
(subjectId,startTime,duration,site,examName)
OUTPUT inserted.examId
INTO @op
VALUES(@subjectId, @startTime, @duration, @site, @examName);
SELECT TOP 1
@examId = colGuid
FROM @op;
INSERT INTO dbo.Exam_Student_Relationship
(examId,studentId)
SELECT @examId, userId
FROM @studentIdList;
INSERT INTO dbo.Exam_Supervisor_Relationship
(examId,supervisorId)
SELECT @examId, userId
FROM @supervisorIdList;
COMMIT
END
根据下面的SQL语句,生成相应的Java代码
DECLARE @studentList UserIdList;
INSERT INTO @studentList
VALUES('38C6D0B1-948D-412F-80BA-5BADDD7ABF53'),
('A3E7AAFF-3C0A-4B27-B92E-15DC5FA479BA');
DECLARE @supervisorList UserIdList;
INSERT INTO @supervisorList
VALUES
('DE6E2A5B-05D9-484A-B225-C8C7265A816B'),
('2EEBE00E-117D-4382-9828-93C7F6922F75');
EXEC dbo.insertIntoExamArrange
'D5C544C2-9983-4805-8599-44DDE095289D','2015-12-18 18:16:30','1:50:33',
'测试楼','编译原理临时考试',@studentList,@supervisorList;
下面是对应上面SQL语句的java代码
public void insertExamArrange(ExamArrange arr, List<User> supervisors,
List<User> students) throws SQLException {
StringBuilder query = new StringBuilder();
if (students.size() > 0) {
query.append(" DECLARE @studentList UserIdList; "
+ " INSERT INTO @studentList VALUES(?) ");
for (int i = 0; i < students.size() - 1; ++i) {
query.append(" ,(?) ");
}
query.append(" ; ");
}else{
assert students.size()==0;
query.append(" DECLARE @studentList UserIdList; ");
}
if (supervisors.size() > 0) {
query.append(" DECLARE @supervisorList UserIdList; "
+ " INSERT INTO @supervisorList VALUES(?) ");
for (int i = 0; i < supervisors.size() - 1; ++i) {
query.append(" ,(?) ");
}
query.append(" ; ");
}else{
assert supervisors.size()==0;
query.append(" DECLARE @supervisorList UserIdList; ");
}
query.append(" EXEC dbo.insertIntoExamArrange "+
" ?,?,?,?,?,@studentList,@supervisorList; ");
try(PreparedStatement pre = getConnection().prepareStatement(query.toString())){
int preIndex = 1;
for(int i=0;i<students.size();++i){
pre.setString(preIndex, students.get(i).getUserId());
++preIndex;
}
for(int i=0;i<supervisors.size();++i){
pre.setString(preIndex, supervisors.get(i).getUserId());
++preIndex;
}
pre.setString(preIndex,arr.getSubjectId());
++preIndex;
pre.setTimestamp(preIndex, arr.getStartTime());
++preIndex;
pre.setTime(preIndex, arr.getDuration());
++preIndex;
pre.setString(preIndex, arr.getSite());
++preIndex;
pre.setString(preIndex, arr.getExamName());
++preIndex;
pre.execute();
}
}