前些天發現了一個巨牛的人工智能學習網站,通俗易懂,風趣幽默,忍不住分享一下給大家。點擊跳轉到教程。
業務 要求批量導入不小于10W條數據到 user 表,但是user表在 insert ?每條數據的同時要 ?insert ?一條對應數據到 customer表,
并且是以 ?customer ?表的主鍵作為 user 表的外鍵。
?
所以想到要一次性獲取多個 序列值,再把對應的序列給不同表,并分別作為兩個表的主鍵和外鍵的值。
?
方法很簡單 ?就一句代碼 :
?
String squence ="select USR_CUSTOMER_SEQ.nextval cust_id from (select 1 from all_objects where rownum <= "+usrlist.size()+")";List<String> squenceList = BatchInsert.selectSql(squence);
"select USR_CUSTOMER_SEQ.nextval cust_id from (select 1 from all_objects where rownum <= "+usrlist.size()+")";List<String> squenceList = BatchInsert.selectSql(squence);
?
usrlist?是解析表格后得到的要導入的 user數據 集合,有多少條數據就取多少個序列值。
selectSql 方法 只是JDBC連接數據庫 執行了這句SQL 并返回了查到的 序列值,拿到這個序列集合就可以根據業務作后續實現了。
?
?
// 單純查詢 public static List<String> selectSql(String sql){Connection conn = null;//定義為空值Statement stmt = null;ResultSet rs = null;conn = getConnection();List<String> list = new ArrayList<String>();try {stmt = conn.createStatement();//創建一個Statement語句對象rs = stmt.executeQuery(sql);//執行sql語句while(rs.next()){list.add(rs.getString("cust_id"));}} catch (SQLException e) {e.printStackTrace();}finally{try {conn.close();stmt.cancel();rs.close();}catch (SQLException e) {e.printStackTrace();}}return list;}
getConnection?方法是獲取數據庫連接:
?
?
public static Connection getConnection(){ //連接數據庫的方法 try { Class.forName("oracle.jdbc.driver.OracleDriver"); //初始化驅動包 conn = DriverManager.getConnection(url, user, password); } catch (Exception e) { e.printStackTrace(); } return conn;}
?
?
?
?
?
另 ?批量導入實現見博文:關聯表多數據的批量insert (批量導入,測試10W條數據用時46秒)
?