mongodb使用三—java中使用连接mongdb

首先我们要使用mongdb首先要引入相应的jar包;

mongo-java-driver-3.2.2.jar 

maven中加入依赖:


    org.mongodb
    mongo-Java-driver
    2.13.0
1.写一个工具类用来连接mongdb数据库 如果数据库不存在mongdb会自己穿建数据库
import java.util.ArrayList;
import java.util.List;

import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

public class MongoManagerUtil {

	/**
	 * 不需要连接认证获取MongoClient
	 * @param host
	 * @param port
	 * @return
	 */
	public MongoClient clientMongo(String host,int port,String dataName){
		try{   
	       // 连接到 mongodb 服务
	         MongoClient mongoClient = new MongoClient( host , port );
	         // 连接到数据库
//	         DB date=mongoClient.getDB(dataName);
	         return mongoClient;
	      }catch(Exception e){
	        System.err.println( e.getClass().getName() + ": " + e.getMessage() );
	        return null;
	      }

		
	}
	/**
	 * 通过连接认证获取MongoClient
	 * @param host
	 * @param port
	 * @param userName
	 * @param dbName
	 * @param psw
	 * @return
	 */
	public MongoClient clientMongo(String host,int port,String userName,String dbName,String psw){
		try{
			ServerAddress serverAddress = new ServerAddress(host,port);
	        List addrs = new ArrayList();
	        addrs.add(serverAddress);
	        //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
	        MongoCredential credential = MongoCredential.createScramSha1Credential(userName, dbName, psw.toCharArray());
	        List credentials = new ArrayList();
	        credentials.add(credential);
	        //通过连接认证获取MongoDB连接
	        MongoClient mongoClient = new MongoClient(addrs,credentials);
	        return mongoClient;
		}catch(Exception e){
			System.err.println( e.getClass().getName() + ": " + e.getMessage() );
	        return null;
		}
	}
}

你可能感兴趣的:(mongdb)