首页 > 数据库技术 > 详细

mongo数据库连接工具类(C#)

时间:2019-03-15 12:58:59      阅读:198      评论:0      收藏:0      [点我收藏+]

Framework版本:.Net Framework 4

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MongoDB.Driver;

namespace ReligionServer.util
{
    public class ConnectionUtil
    {

        private static MongoClient client = null;
        private static MongoServer server = null;
        private static MongoDatabase database = null;
        private static MongoCollection collection = null;
        private static String DATA_SERVER_URL = "mongodb://ip地址:端口/数据库名";//数据库地址
        //mongodb://192.168.1.1:27017/test
        private static String DATA_BASE = "test";//数据库名


        //根据传入的集合名获取到当前集合
        public static MongoCollection GetCollection<T>(String collectionName)
        {
            if (null == server)
            {
                server = getMongoServer();
            }
            if (null == database)
            {
                database = server.GetDatabase(DATA_BASE);
            }
            collection = database.GetCollection<T>(collectionName);
            return collection;
        }

        private static MongoServer getMongoServer()
        {
            if (client == null)
            {
                client = new MongoClient(DATA_SERVER_URL);
            }
            if (server == null)
            {
                server = client.GetServer();
            }
            server.Connect();
            return server;
        }
    }
}

 

mongo数据库连接工具类(C#)

原文:https://www.cnblogs.com/threadj/p/10536273.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!