Mình đang học java và có 1 project yêu cầu :
Đọc 1 file txt.
Cập nhật tất cả các dòng trong file text vào csdl
Hiện tại mình đã xử lý được rồi nhưng do insert lần lượt từng dòng nên để insert hết tất cả các dòng rất lâu. 300000 dòng mất 1h
Mình muốn tạo 1 thread pool 100 thread để gửi lệnh insert dữ liệu cùng 1 lúc để đẩy nhanh quá trình.
Project gồm
Class Kết nối csdl
Mã:
public static Connection getOracleConnection(String hostName, String sid,
String userName, String password) throws ClassNotFoundException,
SQLException {
log.debug("Begin connect.");
Class.forName("oracle.jdbc.driver.OracleDriver");
String connectionURL = "jdbc:oracle:thin:@" + hostName + ":1521:" + sid;
Connection conn = DriverManager.getConnection(connectionURL, userName,
password);
log.debug("Connect success!");
return conn;
}
Class đọc file text và tạo thread để Insert dữ liệu
Mã:
public class ReadUpdate implements Runnable{
private static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger("ReadFile");
File file;
ExecutorService executor = Executors.newFixedThreadPool(100);
@Override
public void run() {
try {
Connection conn = data.getOracleConnection()
try (BufferedReader br = new BufferedReader(new FileReader(file.getAbsolutePath()))) {
String line;
int i=0;
log.info("Start read and update file: " + fileName);
while ((line = br.readLine()) != null) {
Runnable Insert = new InsertDT(conn, line);
executor.execute(Insert);
}
log.info("Finish reading: " + fileName);
} catch (IOException ex) {
log.fatal("ReadFile IOException: " + ex);
} catch (Exception ex) {//SQLException | ClassNotFoundException ex) {
log.fatal("Connect Error: " + ex);
}
}
}
và class để insert
Mã:
public class InsertDT implements Runnable{
private static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger("InsertDT");
private String line
Connection conn = null;
CallableStatement statement;
public InsertDT(Connection _conn, String _line){
this.conn = _conn;
this.line = _line;
}
@Override
public void run() {
try {
try {
this.statement = conn.prepareCall("{ CALL PKG_DMS_TRANSACTION_V2.PROC_INSERT_VIETTEL_TRANSLOG (?,?,?,?,?,?,?,?,?)}");
statement.setString("Data", line);
statement.executeUpdate();
} catch (Exception ex) {
}
} catch (SQLException | ClassNotFoundException ex) {
log.error(ex);
}
}
}
Nhưng khi dùng thread như trên thì thời gian insert dữ liệu không giảm. Mọi người có thể góp ý gì về code để đẩy nhanh quá trình insert dữ liệu không.
View more random threads:
Thông qua phân tích dữ liệu Google từ 86 quốc gia, mới đây, một công ty tại Anh đã công bố bảng xếp hạng kích tấc "cậu nhỏ" của các nước trên thế giới. Kết quả, hầu hết các nước xếp ở nhóm đầu của...
"Chim" của chàng trai Việt thuộc...