我正在尝试在MySQL数据库中插入多条记录,但是即使我在循环中准备了多个语句,我的代码也只能将一条记录插入MySQL数据库。请帮助我哪里我错了。我从2周开始搜索此答案。
这是我的代码。UploadServletClass.java。
String firstName = request.getParameter("firstname");
String lastName = request.getParameter("lastname");
String fileName = "";
String path = folderName + File.separator + fileName;
con = DB.getConnection();
List < Part > fileParts = request.getParts().stream().filter(part - > "file".equals(part.getName())).collect(Collectors.toList());
for (Part filePart: fileParts) {
fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
filePart.write(uploadPath + File.separator + fileName);
InputStream ins = filePart.getInputStream();
String sql = "insert into newfiles(firstname,lastname,filename,path) values(?,?,?,?)"; //inserting all values into database
ps = con.prepareStatement(sql);
Files.copy(ins, Paths.get(uploadPath + File.separator + fileName), StandardCopyOption.REPLACE_EXISTING);
}
ps.setString(1, firstName);
ps.setString(2, lastName);
ps.setString(3, fileName);
ps.setString(4, path);
int status = ps.executeUpdate();
if (status > 0) {
System.out.println("File Uploaded Successfully");
System.out.println("Uploaded Path:" + uploadPath);
}
输入此代码:
ps.setString(1, firstName);
ps.setString(2, lastName);
ps.setString(3, fileName);
ps.setString(4, path);
int status = ps.executeUpdate();
if (status > 0) {
System.out.println("File Uploaded Successfully");
System.out.println("Uploaded Path:" + uploadPath);
}
在for循环内。