Simple Batch read of external insert Files, insert into DB, batch insert into db
Package com. tongxiang. item. base. dao; import java. io. bufferedReader; import java. io. file; import java. io. fileNotFoundException; import java. io. fileReader; import java. io. IOException; import java. SQL. connection; import java. SQL. driverManager; import java. SQL. SQLException; import java. SQL. statement; import java. util. arrays; import org. apache. commons. lang. stringUtils; public class ImportFromSql {private static fin Al String URL = "jdbc: oracle: thin: @ xxx. xxx. xxx. xxx: 1521: orcl "; private static final String USER =" user "; private static final String PASSWORD =" password "; private static Connection CONN = null; static {try {Class. forName ("oracle. jdbc. driver. oracleDriver "); CONN = DriverManager. getConnection (URL, USER, PASSWORD);} catch (SQLException e) {e. printStackTrace ();} catch (Exception e) {e. printSta CkTrace () ;}} public static void main (String [] args) throws Exception {try {// insert file data format // C :\\ TEST. SQL // -------------------------- // insert (...) values (...); // insert (...) values (...); // insert (...) values (...); // -------------------------- String sqlFile = "C: \ TEST. SQL "; // Number of batches processed each time int batchCnt = 100; insertSqlBacth (CONN, sqlFile, batchCnt);} finally {CONN. c Lose () ;}/ *** input the connection to execute the SQL script file, in this way, the ** @ param database Connection * @ param file path * @ param number of each batch processing */public static void insertSqlBacth (Connection conn, string sqlFile, int batchCnt) throws Exception {Statement stmt = null; // obtain the File file File = new File (sqlFile) from a given position; BufferedReader reader = null; try {reader = new BufferedReader (new FileReader (file); // The cache String temp = null for each file read; int I = 0; int mod = 0; stmt = conn. createStatement (); while (temp = reader. readLine ())! = Null) {I ++; stmt. addBatch (StringUtils. chomp (temp. trim (), ";"); mod = I % batchCnt; if (mod = 0) {int [] rows = stmt.exe cuteBatch (); conn. commit (); System. out. println ("Row count:" + Arrays. toString (rows); stmt. close (); stmt = conn. createStatement () ;}} if (mod! = 0) {int [] rows = stmt.exe cuteBatch (); conn. commit (); System. out. println ("Row count:" + Arrays. toString (rows); stmt. close () ;}} catch (FileNotFoundException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} finally {// close the file stream if (reader! = Null) {try {reader. close () ;}catch (IOException e) {e. printStackTrace ();}}}}}