2016-11-24 38 views
1

我CONTROLL數據插入或如下MongoDB的支票插入

public boolean addUser(User user) throws Exception { 

    boolean isRegister=false; 

    Connection conn=null; 
    PreparedStatement ps=null; 
    ResultSet rs=null; 

    try{ 

     String sql="insert into users(username,email,pasword) values(?,?,?)"; 

     conn=dataSource.getConnection(); 

     ps=conn.prepareStatement(sql); 

     ps.setString(1, user.getUsername()); 
     ps.setString(2, kullanici.getEmail()); 
     ps.setString(3, kullanici.getPassword()); 

     int success=ps.executeUpdate(); 

     if(success>0){ 
      isRegister=true; 
     } 

     return isRegister; 
    }finally{ 
     baglantiSonlandir(conn, null, ps); 
    } 


} 

如何能夠做到在MongoDB中這個過程在mysql中沒有插入? 我寫了一些代碼,但我沒有實現數據插入或未插入到db.My MongoDb代碼是波紋管;

public boolean addUser(User user) throws Exception { 

    boolean isRegister=false; 

    MongoClient client=null; 
    MongoDatabase database=null; 

    try{ 

     client=new MongoClient("localhost", 27017); 
     database=client.getDatabase("ogryonsis"); 

     MongoCollection collection=database.getCollection("users"); 

     Document document=new Document(); 
     document.put("username", user.getUserName()); 
     document.put("email", user.getEmail()); 
     document.put("password", user.getPassword()); 

     collection.insertOne(document); 

     //int success ->I didnt find for here appropriate code 

     if(success>0){ 
      isRegister=true; 
     } 

     return isRegister; 
    }finally{ 
     client.close(); 
    } 

} 
+0

因爲insertone返回void所以沒有辦法,如果沒有異常被拋出比你可以假設數據已成功寫入,進一步閱讀的嘗試[這個答案](http://stackoverflow.com/questions/40137495 /升級-蒙戈至3-X-嵌件不再視爲返回-寫結果/ 40138542#40138542) –

回答

0

如文檔writen,如果寫入失敗,你會得到MongoWriteConcernExceptionMongoWriteException

你能適應你這樣的代碼:

isRegister=true; 
try { 
    collection.insertOne(document); 
    } 
    catch (MongoServerException ex { 
    isRegister=false; 
    } 
0

insertOne被定義爲無效的方法。理想的方法是將insertOne語句包裝在try-catch塊中。顯然,如果存在任何異常,則插入操作不成功。

MongoWriteException - 如果寫入失敗,原因是特定於插入命令MongoWriteConcernException一些其他故障 - 如果 寫入失敗,原因是無法完成的寫入關注 MongoException - 如果寫入由於一些其他故障失敗

如果您使用Spring,您可以執行此操作。

MongoOperations mongoOperations = getMongoConnection(); 

     try { 
      mongoOperations.insert(order); 
     } catch (DuplicateKeyException de) { 
      de.printStackTrace(); 
     }