2016-04-25 54 views
0

我要在Excel想打印, 「5」,「空指針異常」 「15」,「ZZZZZ例外」 「7」,「XYZ例外」我想用java

打印在Excel例外計數的總數

我從MySQL數據庫中獲取所有異常。

下面的代碼給出了excel文件中所有異常的輸出,但不知道如何對這些異常進行分組?還有一個幫助,這段代碼水平地打印所有數據。像「nullpointer exception」「ZZZZZ異常」「XYZ異常」。

你能幫助我垂直打印它並將所有這些異常與count分組嗎?謝謝。

public class Abcd { 

    public static void main(String[] args) { 

     Connection conn = null; 
     Statement stmt = null; 
     try { 
      Class.forName("com.mysql.jdbc.Driver"); 
      System.out.println("Connecting to database..."); 
      conn = DriverManager.getConnection(
        "jdbc:mysql://10.9.1.1:3306/XXXXX", "Unm", "pass"); 
    System.out.println("Creating statement..."); 
      stmt = conn.createStatement(); 
      ResultSet rs = stmt 
        .executeQuery("select EXCEPTION_MESSAGE from TABLENAME where E_TYPE = 'FAILED' and O_TYPE = 6 and TIME_ >= '2016-4-8 00:00:00' and TIME_ <= '2016-4-11 00:00:00'"); 

      // Excel file generation code 
      String filename = "D:/RONAKExcelFile.xls" ; 
      HSSFWorkbook workbook = new HSSFWorkbook(); 
      HSSFSheet sheet = workbook.createSheet("FirstSheet"); 
      HSSFRow rowhead = sheet.createRow((short) 0); 
      rowhead.createCell(0).setCellValue("List of Exceptions"); 
      HSSFRow row = sheet.createRow((short)1); 
      int i = 0; 
      while (rs.next()) { 
       // Retrieve by column name 
       String msg = rs.getString("EXCEPTION_MESSAGE"); 
       // Display values 
       System.out.println("Exception=> " + msg); 
       row.createCell(i).setCellValue(msg); 
       i++; 
       System.out.println("Length = " + msg.length()); 
      } 
      FileOutputStream fileOut = new FileOutputStream(filename); 
      workbook.write(fileOut); 
      fileOut.close(); 
      System.out.println("Excel file has been generated!"); 
      rs.close(); 
      stmt.close(); 
      conn.close(); 
     } catch (SQLException se) { 
      // Handle errors for JDBC 
      System.out.println("Unable to make connection with database...!"); 
      se.printStackTrace(); 
     } catch (Exception e) { 
      // Handle errors for Class.forName 
      e.printStackTrace(); 
     } finally { 
      // finally block used to close resources 
      try { 
       if (stmt != null) 
        stmt.close(); 
      } catch (SQLException se2) { 
      }// nothing we can do 
      try { 
       if (conn != null) 
        conn.close(); 
      } catch (SQLException se) { 
       se.printStackTrace(); 
      }// end finally try 
     }// end try 
     System.out.println("Goodbye!"); 
    }// end main 
} 

回答

1

幾點建議:

1)使用GROUP BY語句查詢:

SELECT 
    EXCEPTION_MESSAGE, COUNT(*) AS EXCEPTION_COUNT 
FROM 
    .... 
GROUP BY 
    EXCEPTION_MESSAGE; 

2)現在你的ResultSet的每個條目的「目標Excel中一行相匹配」。即您的while循環應如下所示:

for(int i=0; rs.next(); i++) 
{ 
    HSSFRow row = sheet.createRow(i); 
    row.createCell(0).setCellValue(rs.getString("EXCEPTION_MESSAGE")); 
    row.createCell(1).setCellValue(rs.getString("EXCEPTION_COUNT")); 
}