2015-02-04 3 views
0

내가 봤 거든 및 봤하지만 하나의 적절한 작동 예를 찾을 수있다, 결국 내 경우에 mysql을 가져 오기에 this을 변환 여기에 코드입니다 : "총 레코드를 삽입 : 이것은 출력이mysql db에 Excel의 행을 삽입하는 방법은 무엇입니까?

import java.io.*; 
import org.apache.poi.hssf.usermodel.HSSFWorkbook; 
import org.apache.poi.hssf.usermodel.HSSFSheet; 
import org.apache.poi.ss.usermodel.*; 
import org.apache.poi.xssf.usermodel.XSSFCell; 
import java.util.*; 
import java.sql.*; 


public class Import { 

    public static void main(String[] args) throws Exception{     
      /* Create Connection objects */ 
      // Class.forName ("oracle.jdbc.OracleDriver"); 
      Properties connectionProps = new Properties(); 
      connectionProps.put("user", "myUSERNAME"); 
      connectionProps.put("password", "myPASSWORD"); 
      Connection conn = DriverManager.getConnection("jdbc:mysql://" 
        + "serverIP" + ":" + "3306" + "/" + "myDB", 
        connectionProps); 
      PreparedStatement sql_statement = null; 
      String jdbc_insert_sql = "INSERT INTO myTABLE" 
          + "(LastName, FirstName) VALUES" 
          + "(?,?)"; 
      sql_statement = conn.prepareStatement(jdbc_insert_sql); 
      /* We should now load excel objects and loop through the worksheet data */ 
      FileInputStream input_document = new FileInputStream(new File("insert_old.xls")); 
      /* Load workbook */ 
      HSSFWorkbook my_xls_workbook = new HSSFWorkbook(input_document); 
      /* Load worksheet */ 
      HSSFSheet my_worksheet = my_xls_workbook.getSheetAt(0); 
      // we loop through and insert data 
      Iterator<Row> rowIterator = my_worksheet.iterator(); 
      while(rowIterator.hasNext()) { 
        Row row = rowIterator.next(); 
        Iterator<Cell> cellIterator = row.cellIterator(); 
          while(cellIterator.hasNext()) { 
            Cell cell = cellIterator.next(); 
            switch(cell.getCellType()) { 
            case Cell.CELL_TYPE_STRING: //handle string columns 
              sql_statement.setString(1, cell.getStringCellValue());                      
              break; 
            case Cell.CELL_TYPE_NUMERIC: //handle double data 
              sql_statement.setDouble(2,cell.getNumericCellValue()); 
              break; 
            } 

          } 
      // Add the row to a batch processing - standard batch processing example 
      sql_statement.addBatch(); 
      } 
      //We are now ready to perform a bulk batch insert 
      //our Excel has only 4 records, you should set this suitably 
      int[] totalRecords = new int[4]; 
      try { 
        totalRecords = sql_statement.executeBatch(); 
      } catch(BatchUpdateException e) { 
        //you should handle exception for failed records here 
        totalRecords = e.getUpdateCounts(); 
      } 
      System.out.println ("Total records inserted : " + totalRecords.length); 
      /* Close input stream */ 
      input_document.close(); 
      /* Close prepared statement */ 
      sql_statement.close(); 
      /* COMMIT transaction */ 
      // conn.commit(); 
      /* Close connection */ 
      conn.close(); 
    } 
} 

입니다 : 4 "

엑셀 파일에는 4 개의 행과 2 개의 열이 간단한 텍스트로 채워져 있습니다. 나는 불행하게도 아무것도 가져 오지 않는다. 나는이 간단한 삽입 작업을 나중에 더 많은 이미지 파일을 삽입하기 위해 수정하고 싶다. 파일 경로는 xls 파일에 저장 될 것이고,이 버전은 xls 파일로 사용할 필요가있다. xlsx도 있습니다. 내 코드에서 오류를 찾거나 xls 및 xlsx에 대한 더 나은 작업 예제를 제공 할 수 있다면 기쁩니다. 나는 아파치 POI를 사용하고 있습니다.

답변

1

당신은 간단하게이 작업을 수행 할 수 있습니다 파일을 가정을 C에 위치하고 있습니다 : \ filename.xlsx

Connection con = //...Complete connection initialization 
PreparedStatement pre = con.prepareStatement("load data infile 'C:\\filename.xlsx' into table tablename"); 
pre.executeUpdate(); 

이 코드는 다음과 같은 오류를 피하면 완벽하게 작동합니다 : 1. 파일이 있는지 확인을 디렉토리의 루트에 위치하며 예외가 생길 수 있습니다 (예외가 발생할 수 있음) 2. 작은 따옴표로 경로를 인용하십시오.

+0

파일이로드되기 때문에 'local data infile'을 사용해야했습니다. 내 로컬 컴퓨터에 왜 그런지 모르지만 \\ 충분하지 않아서 \\\\ 및 n 빈 행만 DB에 삽입된다는 사실을 알았습니다. – Anarkie

+0

셸에서 mysql에 대한 쿼리를 실행하고 응답을 볼 수 있지만 위의 코드가 제대로 작동하는지 확인할 수 있습니다. 나는 그것을 개별적으로 사용했다. – Elektron

관련 문제