mongo數據庫連接工具類(C#)
阿新 • • 發佈:2019-03-15
style 當前 work tco database ret net tab lec
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#)