2014-10-31 87 views
4

我想在使用JDBC的Oracle 11g數據庫上執行DDL語句。我正在使用Statement類的boolean execute(String SQL)在JDBC中,如何知道DDL語句是否成功執行?

以下是代碼片段執行查詢,並試圖確定查詢結果:

// Create a SQL string 
String dropSql = "DROP TABLE Reviews"; 

stmt = conn.createStatement(); 

// Execute the query 
boolean result = stmt.execute(dropSql); 

// Get the result of the drop operation 
if(result) 
{ 
    // Its a result set 
    System.out.println("Atleast one result set has been returned. Loop through them"); 
} 
else 
{ 
    // Its an update count or no result 
    Integer updateCnt = stmt.getUpdateCount(); 

    if(updateCnt == -1) 
    { 
     // No results 
     System.out.println("No results returned by the query"); 
    } 
    else 
    { 
     // Update Count 
     System.out.println("Update Count: " + updateCnt); 
    } 
} 

我不是一個數據庫的傢伙,但有一種情況:DDL語句將無法執行而不是提出SQLException?如果沒有,那麼我不需要捕獲執行方法返回的內容。如果缺少SQLException,則表示DDL語句成功執行。

,我下面的tutorial recommendeds對DDL語句的使用這種方法:

boolean execute(String SQL) : ....... Use this method to execute SQL DDL statements or when you need to use truly dynamic SQL. 

雖然Jdbc documentation建議執行DDL語句使用int executeUpdate(String sql)。兩者中哪一個更受歡迎?

回答

4

一個失敗的語句總是引發SQLException無論哪種方法來執行它的。 executeUpdate適用於任何不能產生ResultSet的聲明,這使得DDL聲明完美適合該法案。

3

除非你包裝在PL/QSL的DDL和捕獲異常,它會冒泡到JDBC調用。

至於使用哪一個,任何一個正常工作,因爲DDL您都應該忽略返回值。

的DDL不註冊爲「行數」,不像DML,所以只使用try/catch語句捕捉失敗,並承擔在沒有例外的,它是成功的。

相關問題