Ejemplo n.º 1
0
        /// <summary>
        /// 获取数据库连接,返回的连接已经打开(open);在 mvc 框架中不用关闭,框架会自动关闭连接。
        /// 之所以要传入 EntityInfo,因为 ORM 支持多个数据库,不同的类型有可能映射到不同的数据库。
        /// </summary>
        /// <param name="et"></param>
        /// <returns></returns>
        public static IDbConnection getReadOnlyConnection()
        {
            String       dbname = "readonly";
            DatabaseType dbType = DatabaseType.Access;

            foreach (KeyValuePair <String, Object> kv in DbConfig.Instance.DbType)
            {
                dbname = kv.Key;
                dbType = DbTypeChecker.GetFromString(kv.Value.ToString());
                if (kv.Key == "readonly")
                {
                    break;
                }
            }
            String        connectionString = DbConfig.GetConnectionString(dbname);
            IDbConnection connection;
            Dictionary <String, IDbConnection> connections = getConnectionAll();

            connections.TryGetValue(dbname, out connection);
            if (connection == null)
            {
                try
                {
                    connection = DataFactory.GetConnection(connectionString, dbType);
                }
                catch (Exception ex)
                {
                    LogManager.GetLogger().Error("数据库连接字符串错误:" + connectionString);
                    throw ex;
                }
                connection.Open();
                OrmHelper.initCount++;
                LogManager.GetLogger("Class:System.Data.DbContext Method:getConnection").Info("数据库连接已开启【" + OrmHelper.initCount + "】");
                setConnection(dbname, connection);
                if (shouldTransaction())
                {
                    IDbTransaction trans = connection.BeginTransaction();
                    setTransaction(dbname, trans);
                }
                return(connection);
            }
            if (connection.State == ConnectionState.Closed)
            {
                connection.ConnectionString = connectionString;
                connection.Open();
                OrmHelper.initCount++;
                LogManager.GetLogger("Class:System.Data.DbContext Method:getConnection").Info("数据库连接已开启【" + OrmHelper.initCount + "】");
            }
            return(connection);
        }
Ejemplo n.º 2
0
        private static DatabaseType getDbType(String dbname, String connectionString, DbConfig result)
        {
            foreach (KeyValuePair <String, Object> kv in result.DbType)
            {
                if (kv.Key == dbname)
                {
                    return(DbTypeChecker.GetFromString(kv.Value.ToString()));
                }
            }

            DatabaseType dbtype = DbTypeChecker.GetDatabaseType(connectionString);

            return(dbtype);
        }