2011-05-20 116 views
1

請給我舉一個例子,說明如何在jsf bean中的jdbc prepared語句中使用「INSERT INTO ALL STATEMENT」?如何在jdbc prepared語句中使用INSERT INTO ALL語句

其實我想使用單個jsf頁面和每個員工ID使用一個文本框的員工編號的當前員工。

如何使用INSERT INTO ALL語句實現此目的?

以下是我的代碼片段。

AttendanceBean.java:

public class AttendanceBean { 
private int atteid;      
    private String attdname; 
private int attday; 
private int attmonth; 
private int attyear; 

    public static Connection getAttConnection() throws Exception { 
    String driver = "oracle.jdbc.driver.OracleDriver"; 
    String url = "jdbc:oracle:thin:@localhost:1521:globldb3"; 
    String username = "scott"; 
    String password = "tiger"; 
    Class.forName(driver); 
    Connection conn = DriverManager.getConnection(url, username, password); 
    return conn; 
    } 
public String addAttendance(){ 
    Connection conn = null; 
    PreparedStatement pstmt = null; 
    boolean committed = false; 
try { 
    conn = getAttConnection(); 
    conn.setAutoCommit(false); 
    String query = "INSERT ALL INTO attendance VALUES (?,?,?,?,?)"; 
    pstmt = conn.prepareStatement(query); 
    pstmt.setInt(1,this.atteid); 
    pstmt.setString(2,this.attdname); 
    pstmt.setInt(3,this.attday); 
    pstmt.setInt(4,this.attmonth); 
    pstmt.setInt(5,this.attyear); 
      pstmt.executeUpdate(); 
     conn.commit(); 
     conn.setAutoCommit(true); 
     committed = true; 
    return "home.xhtml"; 
    } catch (Exception e) { 
     e.printStackTrace(); 
     return "CRM.xhtml"; 
    } finally { 
      try{ 
       if (!committed) conn.rollback(); 
       if (pstmt != null) pstmt.close(); 
       if (conn != null) conn.close(); 
      }catch(Exception e){ 
       e.printStackTrace(); 
      } 
     } 
     } 
    }  
+0

這個問題與JSF完全無關。在正常的獨立Java類中這樣做會導致完全相同的問題。請仔細標記。 – BalusC 2011-05-20 12:16:47

回答

3

一個多插入正確的SQL語法是:

INSERT INTO 
    tbl (col1, col2, col3) 
VALUES 
    (val1a, val2a, val3a), 
    (val1b, val2b, val3b), 
    (val1c, val2c, val3c), 
    ... 

然而,JDBC,你最好在一個循環中使用PreparedStatement#addBatch(),其次是一個executeBatch()做一個多插入。下面是一個開創性的例子:

private static final String SQL_INSERT = "INSERT INTO tbl (col1, col2, col3) VALUES (?, ?, ?)"; 

public void save(List<Entity> entities) throws SQLException { 
    Connection connection = null; 
    PreparedStatement statement = null; 

    try { 
     connection = database.getConnection(); 
     statement = connection.prepareStatement(SQL_INSERT); 

     for (Entity entity : entities) { 
      statement.setObject(1, entity.getCol1()); 
      statement.setObject(2, entity.getCol2()); 
      statement.setObject(3, entity.getCol3()); 
      statement.addBatch(); 
     } 

     statement.executeBatch(); 
    } finally { 
     if (statement != null) try { statement.close(); } catch (SQLException ignore) {} 
     if (connection != null) try { connection.close(); } catch (SQLException ignore) {} 
    } 
}