简体   繁体   中英

import data from file csv to Oracle without sql

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

Sample code:

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

You will need to download and add opencsv to classpath.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM