簡體   English   中英

prepareStatement可以做和Statement一樣的事情嗎?

[英]Can prepareStatement do the same thing like Statement?

我的數據庫是Oracle。 我知道Statement可以將SQL語句(插入,刪除或更新)混合到一個批處理中。 這是我的代碼。

DBConnection db = new DBConnection();
Connection c = db.getConn();
Statement s = null ;


try
{ 
    String sql = "insert into t1(id, name) values ('10', 'apple')";
    String sql1 = "insert into t1(id, name) values ('14', 'pie')";
    String sql2 = "delete from t1 where id = '10'";
    s = c.createStatement();

    s.addBatch(sql);
    s.addBatch(sql1);
    s.addBatch(sql2);

    int[] re = s.executeBatch();...

我的問題是PreparedStatement可以這樣做嗎? 如何?

您可以通過PreparedStatement.addBatch()創建批處理,也可以通過PreparedStatement.executeBatch執行批處理

有關PreparedStatement的更多信息,請查看文檔

現在,如果我沒記錯,您想執行以下操作:

public void save(List<Entity> elements) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
try {
    connection = database.getConnection();
    statement = connection.prepareStatement(SQL_INSERT);
    for (int i = 0; i < elements.size(); i++) {
        Element element= elements.get(i);
        statement.setString(1, element.getProperty1());
        statement.setString(2, element.getProperty2());
        .....

        statement.addBatch();
        if ((i + 1) % 200 == 0) {
            statement.executeBatch(); // Execute every 200 items.
        }
    }
    statement.executeBatch();
} finally {
    if (statement != null) try { statement.close(); } catch (SQLException e) { //}
    if (connection != null) try { connection.close(); } catch (SQLException e) {//}
}

}

在這種情況下,我每200個項目執行一次,如果您希望自己設置的話。 但是要進行測試,因為它還取決於驅動程序對批處理操作的限制。

聲明:

用於對數據庫的通用訪問。 在運行時使用靜態SQL語句時很有用。 Statement接口不能接受參數。

PreparedStatement:

計划多次使用SQL語句時使用。 PreparedStatement接口在運行時接受輸入參數。

CallableStatement:

當您要訪問數據庫存儲過程時使用。 CallableStatement接口還可以接受運行時輸入參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM