1. 程式人生 > >批量插入返回多個主鍵

批量插入返回多個主鍵

方案一:

批量插入資料並返回id號

public static ResultSet saveHotel(List<hotel> hotels) {
PreparedStatement pstmt = null;
Connection conn = DB.getConnection();
try {
String sql = "insert into t_hotel  values(null , ?,? ,? ,?,? ,? ,?,?,?)";

                        //插入資料時返回的id號 
pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

                        for(Hotel hotel :hotels){
pstmt.setString(1, hotel.getName());
pstmt.setString(2, hotel.getPassword());
pstmt.setString(3, hotel.getAddress());
pstmt.setString(4, hotel.getPhone());
pstmt.setInt(5, hotel.getPrice());
pstmt.setString(6, hotel.getImg());
pstmt.setString(7, hotel.getCuisine());
pstmt.setString(8, hotel.getArea());
pstmt.setString(9, hotel.getStreet());

                        pstmt.addBatch();

                       }
pstmt.executeBatch();

//獲得返回的id號,是一個set

ResultSet keyRs = pstmt.getGeneratedKeys();

                       
} catch (SQLException e) {
e.printStackTrace();
return 0 ;
} finally {
DB.closepStmt(pstmt);
DB.closeConn(conn);
}

                       return keyRs ;

方案二