将数据从文件csv导入Oracle而不使用sql

时间:2017-05-17 10:42:51

标签: java sql oracle

有没有办法使用JAVA将CSV文件导入oracle表?

1 个答案:

答案 0 :(得分:0)

示例代码:

import java.io.*;
import com.opencsv.*;
import java.util.*;
import java.sql.*; 
public class loadcsvinoracle {  
        public static void main(String[] args) throws Exception{                
                /* Create Connection objects */
                Class.forName ("oracle.jdbc.OracleDriver"); 
                Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@//localhost:1521/db12c", "hr", "hr");
                PreparedStatement sql_statement = null;
                String jdbc_insert_sql = "INSERT INTO CSVFILE"
                                + "(COL1, COL2, COL3) VALUES"
                                + "(?,?,?)";
                sql_statement = conn.prepareStatement(jdbc_insert_sql);
                /* Read CSV file in OpenCSV */
                String inputCSVFile = "csvfile.csv";
                CSVReader reader = new CSVReader(new FileReader(inputCSVFile));         
                String [] nextLine; 
                int lnNum = 0; 
                //loop file , add records to batch
                while ((nextLine = reader.readNext()) != null) {
                        lnNum++;
                        /* Bind CSV file input to table columns */
                        sql_statement.setString(1, nextLine[0]);
                        sql_statement.setString(2, nextLine[1]);
                        sql_statement.setString(3, nextLine[2]);
                        // Add the record to batch
                        sql_statement.addBatch();
                        System.out.println ("New line " + nextLine[0] + nextLine[1] + nextLine[2]);
                }                       
                //We are now ready to perform a bulk batch insert              
                int[] totalRecords = new int[7];
                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 in bulk from CSV file " + totalRecords.length);                
                /* Close prepared statement */
                sql_statement.close();
                /* COMMIT transaction */
                conn.commit();
                /* Close connection */
                conn.close();
        }
}

您需要下载并添加opencsv到classpath。