Search code examples
javasqlimporttransactions

Importing Excel file in Database using java


I am importing the Excel data into my database using java code. Suppose there are more than 200 rows and I want to stop the import.Is it possible to cancel the import in between and rollback all the data which got created in database while importing ?


Solution

  • Yes it is. You just have to deactivate autoCommit and commit or rollback whenever you are done.

    A simple example:

    
     DriverManager.registerDriver(new com.mysql.jdbc.Driver());
     String url = "jdbc:mysql://localhost/mydatabase/icpc";
     Connection conn = DriverManager.getConnection("url", "username", "pass");
    
     // Set the auto commit false. This will execute all
     // SQL statements as individual transactions
     con.setAutoCommit(false);
    
     // Do your thing with the Excel file...
    
     // In the end you could either rollback or commit like this
     conn.commit();
    
     // OR
    
     conn.rollback();