gpt4 book ai didi

java - MongoDB 检查插入

转载 作者:可可西里 更新时间:2023-11-01 10:19:26 24 4
gpt4 key购买 nike

我控制mysql中插入或不插入的数据如下

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 中实现这个过程?我写了一些代码,但我没有实现将数据插入或不插入到 db。我的 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();
}

}

最佳答案

如文档中所写,如果写入失败,您将得到 MongoWriteConcernExceptionMongoWriteException

您可以像这样调整您的代码:

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

关于java - MongoDB 检查插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40792012/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com