2011-09-26 23 views
0

我正在使用log4j在java桌面應用程序(在Eclipse上創建此應用程序)中記錄消息。在java中使用try-catch捕獲sql相關錯誤(記錄錯誤)

工作的一部分是使用JDBC將csv(逗號分隔值)數據批量插入到sql server數據庫中。

我想要在批量插入過程中捕獲任何錯誤,並記錄發生錯誤的特定記錄的詳細信息,然後恢復批量插入工作。

下面給出了進行批量插入的相關代碼,我如何編寫異常處理來執行我所期望的操作?還有一個問題 - 當前堆棧跟蹤被打印到控制檯上,我想將其記錄到日誌文件中(使用Log4j)...我該怎麼做?

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); 
     } 
} 

回答