0

I am using log4j for logging messages in a java desktop application (working on Eclipse to create this app).

One part of the work is to do bulk insertion of csv (comma separated values) data into sql server database using JDBC.

I want to catch any error during the bulk inserts, and log the details of specific record for which the error occurred, and then resume the work of bulk insertion.

The relevant code which does the bulk insertion is given below, how do I code the exception handling to do what I desire? One more question- currently the stack trace is printed onto console, I want to log this into log file (using Log4j)... How do I do this?

public void insertdata(String filename)
{
    String path = System.getProperty("user.dir");
    String createString = "BULK INSERT Assignors FROM  '" + path + "\\" +filename+ ".txt' WITH (FIELDTERMINATOR = ',')";   
    System.out.println(" Just before try block...");

    try  
       { 
            // Load the SQLServerDriver class, build the 
            // connection string, and get a connection 
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 
            String connectionUrl = "jdbc:sqlserver://ARVIND-PC\\SQLEXPRESS;" + 
                                    "database=test01;" + 
                                    "integratedSecurity=true;"; 
            Connection con = DriverManager.getConnection(connectionUrl); 
            System.out.println("Connected."); 

            // Create and execute an SQL statement that returns some data.  
            String SQL = "BULK INSERT dbo.Assignor FROM  '" + path + "\\" +filename+ ".txt' WITH (FIELDTERMINATOR = ',')";

            Statement stmt = con.createStatement();  
            //ResultSet rs = stmt.executeQuery(SQL);
            Integer no_exec;
            no_exec=stmt.executeUpdate(SQL);
            // Iterate through the data in the result set and display it.  
            //while (rs.next())  
            //{  
            // //System.out.println(rs.getString(1) + " " + rs.getString(2));
            //  System.out.println(" Going through data");
            //}

            System.out.println("Number of rows updated by the query=" + no_exec);
       }  
       catch(Exception e)  
       { 
            System.out.println(e.getMessage()); 
            e.printStackTrace(); 
            System.exit(0);  
       } 
}

1 Answer 1

1

Did you read Short Introduction to log4j? You need a log instance, and from there the rest is cake.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.