I have a program where I extract some records from a PDF file, then I proceed to insert those records into a table in MySQL.
One of my main concern is if there is an error under any circumstances during the inserting to table. Let's say if I am inserting 1000 records from a file into the table and halfway, something bad happens. So does it auto rollback or do I need to include a "Begin Transaction and Commit Transaction"
statement?
If so, how do I initiate a rollback inside Java? I am thinking of writing a rollback function just to achieve this.
My code:
public void index(String path) throws Exception {
PDDocument document = PDDocument.load(new File(path));
if (!document.isEncrypted()) {
PDFTextStripper tStripper = new PDFTextStripper();
String pdfFileInText = tStripper.getText(document);
String lines[] = pdfFileInText.split("\\r?\\n");
for (String line : lines) {
String[] words = line.split(" ");
String sql="insert IGNORE into test.indextable values (?,?)";
// con.connect().setAutoCommit(false);
preparedStatement = con.connect().prepareStatement(sql);
int i=0;
for (String word : words) {
// check if one or more special characters at end of string then remove OR
// check special characters in beginning of the string then remove
// insert every word directly to table db
word=word.replaceAll("([\\W]+$)|(^[\\W]+)", "");
preparedStatement.setString(1, path);
preparedStatement.setString(2, word);
preparedStatement.addBatch();
i++;
if (i % 1000 == 0) {
preparedStatement.executeBatch();
System.out.print("Add Thousand");
}
}
if (i > 0) {
preparedStatement.executeBatch();
System.out.print("Add Remaining");
}
}
}
// con.connect().commit();
preparedStatement.close();
System.out.println("Successfully commited changes to the database!");
}
This function above will be called by another function to be executed and the try and catch exception is in the caller function.
My rollback function:
// function to undo entries in inverted file on error indexing
public void rollbackEntries() throws Exception {
con.connect().rollback();
System.out.println("Successfully rolled back changes from the database!");
}
I appreciate any suggestions.