Connect to MongoDB using Java, operate on mongodb, and connect to MongoDB using java

Source: Internet
Author: User

Connect to MongoDB using Java, operate on mongodb, and connect to MongoDB using java

Java is very simple to connect to MongoDB. Specifically, there are two steps:
1: import the java-mongo driver package to the new project.
:

2: create a link help class to complete the link operation

Package com. yc. mongodb; import java. util. iterator; import java. util. set; import com. mongodb. basicDBObject; import com. mongodb. DB; import com. mongodb. DBCollection; import com. mongodb. DBCursor; import com. mongodb. DBObject; import com. mongodb. mongo; import com. mongodb. writeResult; public class extends link2 {public static void main (String [] args) {Mongo mongo = null; DB db = null; try {// link to the mongo server mongo = new Mongo ("127.0.0.1", 27017); // obtain the database object based on the mongodb Database Name and connect to the database yc DB = mongo. getDB ("yc"); // send the request to obtain the db. requestStart (); // obtain the Set <String> collections = db. getCollectionNames (); Iterator itr = collections. iterator (); // iterative output while (itr. hasNext () {System. out. println (itr. next ();} DBCollection dbObject = db. getCollection ("yc"); DBObject object = null; // Add object = new BasicDBObject (); object. put ("_ id", 1003); object. put ("n Ame "," Zhang San "); object. put ("sex", "male"); WriteResult rs = dbObject. insert (object); object. put ("_ id", 1002); // remove dbObject. remove (new BasicDBObject (); // query all DBCursor cursor = dbObject. find (); while (cursor. hasNext () {object = cursor. next (); System. out. println (object) ;}} catch (Exception e) {e. printStackTrace ();} finally {if (mongo! = Null) {mongo. close ();}}}}

The running result is as follows:

At this point, it is actually ready for use. The code coupling is too high, the function binding is too serious, and it is not convenient to call,
Then encapsulate it.

First define an attribute file:

It defines some basic configurations, such as the user name, database name, ip address, and port.
Next, define a class to read the file. It is better to define the file as a singleton,

package com.yc.mongodb;import java.io.IOException;import java.io.InputStream;import java.util.Properties;@SuppressWarnings("serial")public class MyPro extends Properties{    private static MyPro instanece=new MyPro();    private MyPro(){        InputStream is=MyPro.class.getResourceAsStream("/db.properties");        try {            this.load(is);        } catch (IOException e) {            e.printStackTrace();        }finally{            if(is!=null){                try {                    is.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }    public static MyPro getInstance(){        return instanece;    }}

Define a DBHelper class like oracle to encapsulate data operations:
As follows:

Package com. yc. mongodb; import java.net. unknownHostException; import com. mongodb. DB; import com. mongodb. DBCollection; import com. mongodb. mongo; import com. mongodb. unknown exception; public class DBHelper {private static Mongo mongo = null; private DB db = null; private DBCollection collection = null; static {try {mongo = new Mongo (MyPro. getInstance (). getProperty ("ip"), Integer. parseInt (MyPro. getInstance (). getPrope Rty ("port");} catch (NumberFormatException e) {e. printStackTrace ();} catch (UnknownHostException e) {e. printStackTrace ();} catch (except exception e) {e. printStackTrace ();} System. out. println (mongo);}/***** @ param dbName * @ param name * @ param pwd * @ return */public boolean getDB (String dbName, String name, String pwd) {db = mongo. getDB (dbName); if (name! = Null &&! "". Equals (name) & pwd! = Null &&! "". Equals (pwd) {if (db. authenticate (name, pwd. toCharArray () {return true;} else {return false;} else {// check whether the user name and password String uname = MyPro are specified in the configuration file. getInstance (). getProperty ("uname"); String pwds = MyPro. getInstance (). getProperty ("password"); if (uname! = Null &&! "". Equals (uname) & pwds! = Null &&! "". Equals (pwds) {if (db. authenticate (uname, pwds. toCharArray () {return true;} else {return false ;}} return true ;} /*** close connection ** @ param mongo */public void closeAll (Mongo mongo) {if (mongo! = Null) {mongo. close () ;}}// you can use method overload to Transfer Parameters in different cases/*** obtain the specified set * @ param collectionName: the set to be linked * @ param dbName: database * @ return */public DBCollection getDBCollection (String collectionName, String dbName) {DBCollection dBCollection = null; if (getDB (dbName, null, null) {db. requestStart (); if (collectionName = null) {// if it is null, search for collectionName = MyPro in the configuration file. getInstance (). getProperty ("collectionName");} dBCollection = db. getCollection (collectionName);} else {// throw new RuntimeException ("database connection failed");} return dBCollection ;} /***** @ param collectionName * @ param dbName * @ param name * @ param password * @ return */public DBCollection getDBCollection (String collectionName, String dbName, String name, string password) {DBCollection dBCollection = null; if (getDB (dbName, name, password) {db. requestStart (); if (collectionName = null) {// if it is null, search for collectionName = MyPro in the configuration file. getInstance (). getProperty ("collectionName");} dBCollection = db. getCollection (collectionName);} else {// throw new RuntimeException ("database connection failed");} return dBCollection ;} /*** only pass the set name * @ param collectionName * @ return */public DBCollection getDBCollection (String collectionName) {DBCollection dBCollection DBCollection = null; String dbName = MyPro. getInstance (). getProperty ("dbName"); if (getDB (dbName, null, null) {db. requestStart (); if (collectionName = null) {// if it is null, search for collectionName = MyPro in the configuration file. getInstance (). getProperty ("collectionName");} dBCollection = db. getCollection (collectionName);} else {// throw new RuntimeException ("database connection failed");} return dBCollection ;}

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.