2014-06-24 34 views
14

我正在使用Java連接到MySQL數據庫。我試圖插入或更新數據到數據庫中。如何使用Java和MySQL確定插入或更新是否成功?

即使我很確定插入是否成功,它將返回false。

根據「execute」API,如果第一個結果是ResultSet對象,則返回值爲「true」;如果它是更新計數或沒有結果,則返回false。

如何確定我的插入或更新是否成功?

public boolean insertSelections(String selection, String name){ 
     String sql ="INSERT INTO WORKREPORT VALUES (?,?,?,?,?)"; 
     boolean action = false; 
     try { 
      PreparedStatement stmt = conn.prepareStatement(sql); 
      SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy:MM:dd hh:mm:ss"); 
      String formatDate = dateFormat.format(new java.util.Date(System.currentTimeMillis())); 
      java.util.Date mDate = dateFormat.parse(formatDate); 
      java.sql.Timestamp timeStamp = new java.sql.Timestamp(System.currentTimeMillis()); 
//   Date time= new Date(mDate.getTime()); 

      stmt.setInt(1, Integer.parseInt(getNumberByName(name).trim())); 
      stmt.setString(2, name); 
//   stmt.setDate(3, time); 
      stmt.setTimestamp(3, timeStamp); 
      stmt.setString(4, selection); 
      stmt.setString(5, "N/A"); 
      action = stmt.execute(); 
     } catch (SQLException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (ParseException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     return action; 
    } 
+1

嘗試用'stmt.executeUpdate();'更新操作(INSERT,UPDATE,DELETE)''。 –

回答

19

由於您使用PreparedStatement你可以打電話executeUpdate() -

int count = stmt.executeUpdate(); 
action = (count > 0); // <-- something like this. 

根據JavaDoc(返回)以上鍊接,加上強調,

:(1)行數 SQL語句(DML)語句或(2)0不返回任何SQL語句。

如果你想插入大量的條目,我寧願addBatch()executeBatch()

-1

如果你沒有得到一個例外,我認爲查詢就OK了。 或者,您可以使用executeUpdate()(http://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html#executeUpdate()

如果需要,您可以執行select count(*)do validate number of records。

+0

我目前正在運行一個刪除查詢,應該刪除我的測試中的1條記錄。查詢確實通過,但它確實返回了0個已更改的記錄。因此這是不正確的。 SELECT count(*)可以工作,但不是必需的。 –

9

首先,這你應該知道:

布爾的execute() 在執行此PreparedStatement對象的SQL語句,它可以是任何種類的SQL語句。

ResultSet executeQuery() 執行此PreparedStatement對象中的SQL查詢並返回由查詢生成的ResultSet對象。

INT的executeUpdate() 執行在此PreparedStatement對象的SQL語句,它必須是一個SQL INSERT,UPDATE或DELETE語句;或者不返回任何內容的SQL語句,如DDL語句。

 int i=stmt.executeUpdate(); 
     if(i>0) 
     { 
       System.out.println("success"); 
     } 
       else 
     { 
      System.out.println("stuck somewhere"); 

     } 

試試這個,看看是否插入正在發生或不

0

試試這個,你是否想知道數據是否已插入,如果記錄插入它返回true否則爲false 。

if(action > 0){ 
     return true; 
    }else{ 
     return false; 
     } 
相關問題