完成程序填空,实例化一个mongo客户端,服务器地址:localhost(本地),端口号:27017,实例化一个mongo数据库mycol, 创建集合 test,获取数据库中集合test,在集合test中插入内容为"name","zhangsan"的一条文档,打印输出“Connect to database successfully”,利用try-catch机制捕获异常,输出打印错误信息。 public class MongoDBJDBC{ public static void main( String args[] ){ try{ // 连接到 mongodb 服务 MongoClient mongoClient = new MongoClient( __(1)__); // 连接到数据库 MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol"); mongoDatabase. _____(2)___("test"); MongoCollection collection = mongoDatabase.getCollection("test"); collection.insertOne(new Document().__(3)__("name","zhangsan")); System.out.println("Connect to database successfully"); FindIterable findIterable = collection.find(); MongoCursor mongoCursor = findIterable.__(4)__; while(mongoCursor.__(5)__){ System.out.printIn(mongoCursor.next()); } System.out.printIn("文档插入成功"); }catch(Exception e){ System.err.printIn( e.getClass().getName() + ": "' + e.getMessage() );}}}
时间: 2024-03-24 21:36:04 浏览: 66
MongoDB可视化客户端工具和Java开发所需mongo-2.8.0.jar
以下是代码的完整版,其中__(1)__、__(2)__、__(3)__、__(4)__、__(5)__需要填入相应的内容:
```
public class MongoDBJDBC{
public static void main( String args[] ){
try{
// 连接到 mongodb 服务
MongoClient mongoClient = new MongoClient("localhost", 27017 ); // (1)
// 连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
mongoDatabase.createCollection("test");
MongoCollection<Document> collection = mongoDatabase.getCollection("test");
collection.insertOne(new Document().append("name","zhangsan")); // (3)
System.out.println("Connect to database successfully");
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator(); // (4)
while(mongoCursor.hasNext()){
System.out.println(mongoCursor.next());
}
System.out.println("文档插入成功");
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
```
阅读全文