美文网首页
mongodb的密码链接

mongodb的密码链接

作者: 小黑泡泡 | 来源:发表于2017-12-06 17:59 被阅读0次

    * 无密码连接mongodb服务

    */

    public void connectToMongoNoPasswd() throws Exception{

    //连接到 mongodb 服务

    MongoClient mongoClient = new MongoClient( "192.168.1.5" , 27017 );

    //连接到数据库

    MongoDatabase mongoDatabase = mongoClient.getDatabase("col");

    System.out.println("Connect to database successfully");

    }

    /**

    * 设置密码连接mongodb服务

    */

    public void connectToMongoByPasswd() throws Exception{

    //ServerAddress()两个参数分别为 服务器地址 和 端口

    ServerAddress serverAddress = new ServerAddress("192.168.1.5",27017);

    List addrs = new ArrayList();

    addrs.add(serverAddress);

    //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码

    MongoCredential credential = MongoCredential.createScramSha1Credential("username",

    "databaseName", "password".toCharArray());

    List credentials = new ArrayList();

    credentials.add(credential);

    //通过连接认证获取MongoDB连接

    MongoClient mongoClient = new MongoClient(addrs,credentials);

    //连接到数据库

    MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");

    System.out.println("Connect to database successfully");

    }

    MongoDB使用教程系列文章--Driver原理(初始化) 

    初始化配置地址: https://yq.aliyun.com/articles/3218

    相关文章

      网友评论

          本文标题:mongodb的密码链接

          本文链接:https://www.haomeiwen.com/subject/sqvxixtx.html