我刚刚学会了通过Eclipse调试器遍历我的代码。
但是,我不知道为什么这个过程一直回到第71行 - ps.executeUpdate()
,而控制台在第79行提到了错误,并且还提到了其他类的其他错误行。希望有人能告诉我发生了什么。
这是subjectDAOImpl上的代码:
public void insertSubject(subject s) throws MyDataException {
try {
openConnection();
String qry = INSERT_QRY1;
//"INSERT INTO hi5project.subject(subject)VALUES (?)";
ps = connection.prepareStatement(qry);
int i = 0;
String[] sub = new String[3];
while(i < sub.length){
String e = s.getSubj();
ps.setString(1, e);
ps.executeUpdate(); - line 71
}
if (ps !=null )
closeConnection();
}catch (SQLException e) {
e.printStackTrace();
throw new MyDataException("DB Error"); - line79
}
}
控制器:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
subject m = new subject();
manager mgr = new manager();
try {
String[] sub = request.getParameterValues("subject");
int i = 0;
while (i < sub.length) {
sub[i] = m.getSubj();
mgr.insertSubject(m);
out.println("Successful registered subject");
}
} catch (Exception ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
}
答案 0 :(得分:2)
因为您正在执行多个语句,我建议使用Statement Batching
我不知道你为什么使用:
String[] sub = request.getParameterValues("subject");
int i = 0;
while (i < sub.length) {
sub[i] = m.getSubj();
mgr.insertSubject(m);
out.println("Successful registered subject");
}
我认为你只需要使用:
String[] sub = request.getParameterValues("subject");
mgr.insertSubject(m);
out.println("Successful registered subject");
并且您可以将insertSubject的签名更改为insertSubject(String[] sub)
,现在您可以使用此批处理来插入数据:
connection.setAutoCommit(false);
try (PreparedStatement insert = connection.prepareStatement(qry)) {
for (String s : sub) {//loop throw your array
insert.setString(1, s);
insert.addBatch();
}
insert.executeBatch();//executing the batch
}
connection.commit();//commit statements to apply changes
注意你的循环无法完成,因为你没有增加i
,我已经改变了一点你的逻辑希望这可以帮助你,另外一件事似乎是子数组始终为空,因此您始终使用null