I would like to pass on the getGneratedKeys
which is also known as last_generated_id
from the current Java class to the next class. However, I am quite clueless on how to store and collect the ID to the next Java class for this class to use.
The scenario is that insert.jsp
will insert all the strings and int into my mysql database. The 2nd page UserImage.jsp
will upload the image into the same table and same record as insert.jsp
.
This means that UserImage
query would be an update query instead of an insert query.
Save.java
(associated class for insert.jsp
):
public String execute()
{
int i = 0; //SELECT LAST_INSERT_ID();
try{
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull","root","8899");
String s = "insert into usertable(userNRIC, userName, userEmail, userPW, userContact, userAddress, catID, catTypeID, sectionID, status"
+ ") values (?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) ";
PreparedStatement ps=con.prepareStatement(s, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, mb.getUserNRIC());
ps.setString(2, mb.getUserName());
ps.setString(3, mb.getUserEmail());
ps.setString(4, mb.getUserPW());
ps.setInt(5, mb.getUserContact());
ps.setString(6, mb.getUserAddress());
ps.setInt(7, mb.getCatID());
ps.setInt(8, mb.getCatTypeID());
ps.setInt(9, mb.getSectionID());
ps.setString(10, mb.getStatus());
ps.executeUpdate();
con.commit();
ResultSet rs = ps.getGeneratedKeys();
if (rs != null && rs.next()) {
i = rs.getInt(1);
//ps.setInt(i, mb.getUserID("UserID"));
}
ps.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
addActionError(e.getMessage());
}
return SUCCESS;
}
FileUploadAction.java
(associated class for UserImage.jsp
):
public String execute(){
int i = 0;
connection = getConnection();
String query = "update usertable set userPhoto=? where userID=?";
try {
String filePath = servletRequest.getSession().getServletContext().getRealPath("/");
System.out.println("Server path:" + filePath);
File fileToCreate = new File(filePath, this.userImageFileName);
FileUtils.copyFile(this.userImage, fileToCreate);
//String uniqueFileName = fileToCreate.getPath();
pst = connection.prepareStatement(query);
pst.setString(1, this.userImageFileName);
i = pst.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
addActionError(e.getMessage());
return INPUT;
}
return SUCCESS;
}