2014-09-25 34 views
0

如果我想選擇我的數據庫中的東西,我可以在ResultSet中執行查詢,然後返回以查看我得到的結果。但是,如果要插入或更新行,我該如何執行檢查?
如何查看數據庫返回的內容?如果它影響什麼?檢查更新查詢是否影響到行

public static boolean doUpdate(String statement) { 
    openConnection(); 
    try { 
     stmt = conn.createStatement(); 
     stmt.executeUpdate(statement); 
     closeConnection(); 
     return true; 
    } catch (SQLException ex) { 
     System.out.println(DBhandler.class.getName()+"\n"+ex); 
     closeConnection(); 
    } 
    return false; 
} 

我曾試圖給該函數的布爾返回值,但如果更新/插入工作或不試的代碼會繼續不管。

+2

不[關於Statement.executeUpdate](http://docs.oracle.com/javase/8/docs/api/java/sql/Statement.html#executeUpdate-java.lang.String-)您的更新已經返回受影響的行數? – 2014-09-25 18:03:29

+0

你是對的:) – 2014-09-25 19:52:10

回答

2

executeUpdate命令返回受影響的行數。如果至少有一行受到影響,請保留該數字並返回true。此外,您應該在finally塊中關閉連接,因此即使發生異常,也會執行closeConnection()。看看下面的代碼。

public static boolean doUpdate(String statement) { 
    boolean result = false; 
    openConnection(); 
    try { 
     stmt = conn.createStatement(); 
     result = stmt.executeUpdate(statement) > 0; 
    } catch (SQLException ex) { 
     System.out.println(DBhandler.class.getName()+"\n"+ex); 
    } finally { 
     closeConnection(); 
    } 

    return result; 
} 
+0

無論發生什麼,這都會返回false ..? – 2014-09-25 19:59:30

+0

啊哈!這是因爲你在你的例子中運行了兩次executeUpdate!現在作品精湛:)謝謝 – 2014-09-25 20:46:12

+0

哎呀,對不起。 – alkis 2014-09-25 21:05:39

3

executeUpdate method返回受影響的適合執行的SQL語句的行數。

返回:

:(1)該行數SQL數據操作語言(DML)語句(2)0表示不返回任何

int rows = executeUpdate(statement); 

然後你的SQL語句可以查看rows以查看它是否爲0,並適當返回boolean

+0

我剛試過這個,即使更新查詢有效,它在我的行變量中返回0? – 2014-09-25 20:05:00

相關問題