コード例 #1
0
        internal async ValueTask <bool> ExecuteAsync(IQueryBuilder queryBuilder)
        {
            DbTransaction transaction = null;

            try
            {
                if (ApiMode)
                {
                    var affectedRows = await apiClient.GetResponse(queryBuilder);

                    return(Convert.ToInt32(affectedRows[0]?[0]) > 0);
                }
                else
                {
                    using (var connection = await CreateConnectionAsync())
                        using (transaction = Connector.Settings.UseTransactions ? connection.BeginTransaction(IsolationLevel.ReadCommitted) : null)
                        {
                            using var cmd = CreateSqlCommand(connection, transaction, queryBuilder);
                            var affectedRows = await cmd.ExecuteNonQueryAsync();

                            transaction?.Commit();

                            return(affectedRows > 0);
                        }
                }
            }
            catch (Exception ex)
            {
                Log.Message(LogTypes.Error, ex.ToString());

                transaction?.Rollback();

                return(false);
            }
        }
コード例 #2
0
        async ValueTask <object[][]> ExecuteFromApiAsync(IQueryBuilder queryBuilder, ApiRequest apiRequest)
        {
            DbTransaction transaction = null;

            try
            {
                using (var connection = await CreateConnectionAsync())
                    using (transaction = Connector.Settings.UseTransactions ? connection.BeginTransaction(IsolationLevel.ReadCommitted) : null)
                    {
                        using var cmd = CreateSqlCommand(connection, transaction, apiRequest);
                        var affectedRows = await cmd.ExecuteNonQueryAsync();

                        transaction?.Commit();

                        return(new object[1][] { new object[] { affectedRows } });
                    }
            }
            catch (Exception ex)
            {
                Log.Message(LogTypes.Error, ex.ToString());

                transaction?.Rollback();

                return(null);
            }
        }
コード例 #3
0
        internal async Task <DbDataReader> SelectAsync(string sql, params object[] args)
        {
            var connection = await CreateConnectionAsync();

            DbTransaction trans = transactions ? connection.BeginTransaction(IsolationLevel.ReadCommitted) : null;

            try
            {
                // Usage of an 'using' statement closes the connection too early.
                // Let the calling method dispose the command for us and close the connection with the correct CommandBehavior.
                DbDataReader dbDataReader = await CreateSqlCommand(connection, trans, sql, args).ExecuteReaderAsync(CommandBehavior.CloseConnection);

                trans?.Commit();

                return(dbDataReader);
            }
            catch (Exception ex)
            {
                Log.Message(LogTypes.Error, ex.ToString());

                trans?.Rollback();

                return(null);
            }
        }
コード例 #4
0
ファイル: BaseIndexer.cs プロジェクト: FangYuFan/fastSQL
 public IIndexer Commit()
 {
     Transaction?.Commit();
     Transaction?.Dispose();
     Transaction = null;
     return(this);
 }
コード例 #5
0
ファイル: DBContext.cs プロジェクト: zllzllzlzl/BlogDemoCode
        /// <summary>
        /// 事务提交
        /// </summary>
        public void CommitTransaction()
        {
            DbTransaction?.Commit();
            Committed = true;

            Dispose();
        }
コード例 #6
0
        public Task CommitAsync(CancellationToken cancellationToken)
        {
            ThrowIfDisposed();

            _transaction?.Commit();

            return(Task.FromResult(0));
        }
コード例 #7
0
ファイル: AbstractSqlContext.cs プロジェクト: drony/Ark.Tools
 public virtual void Commit()
 {
     lock (_connection)
     {
         _transaction?.Commit();
         _transaction?.Dispose();
         _transaction = null;
     }
 }
コード例 #8
0
        public void Commit()
        {
            _transaction?.Commit();
            _transaction?.Dispose();
            _connection?.Dispose();

            _transaction = null;
            _connection  = null;
        }
コード例 #9
0
        /// <summary>
        /// Executes pre-migration scripts.
        /// </summary>
        /// <returns>True if pre-migrations were executed, otherwise - false.</returns>
        /// <exception cref="MigrationException"></exception>
        private async Task <bool> ExecutePreMigrationScriptsAsync(CancellationToken token = default)
        {
            var desiredMigrations = _preMigrations
                                    .OrderBy(x => x.Version)
                                    .ToArray();

            if (desiredMigrations.Length == 0)
            {
                return(false);
            }

            foreach (var migration in desiredMigrations)
            {
                token.ThrowIfCancellationRequested();

                DbTransaction?transaction = null;

                await _dbProvider.CloseConnectionAsync();

                await _dbProvider.OpenConnectionAsync(token);

                try
                {
                    _logger?.LogInformation(
                        $"Executing pre-migration script {migration.Version} (\"{migration.Comment}\") for database \"{_dbProvider.DbName}\"...");

                    if (migration.IsTransactionRequired)
                    {
                        transaction = _dbProvider.BeginTransaction();
                    }
                    else
                    {
                        _logger?.LogWarning($"Transaction is disabled for pre-migration {migration.Version}");
                    }

                    await migration.UpgradeAsync(transaction, token);

                    transaction?.Commit();

                    _logger?.LogInformation(
                        $"Executing pre-migration script {migration.Version} for database \"{_dbProvider.DbName}\" completed.");
                }
                catch (Exception e)
                {
                    throw new MigrationException(
                              MigrationError.MigratingError,
                              $"Error while executing pre-migration to {migration.Version} for database \"{_dbProvider.DbName}\": {e.Message}",
                              e);
                }
                finally
                {
                    transaction?.Dispose();
                }
            }
            return(true);
        }
コード例 #10
0
        /// <summary>
        /// 提交数据库事务
        /// </summary>
        public void Commit()
        {
            TranCount--;

            if (TranCount == 0)
            {
                _Transaction?.Commit();
                _Transaction?.Dispose();
                _Transaction = null;
            }
        }
コード例 #11
0
        void IEnlistmentNotification.Commit(Enlistment enlistment)
        {
            _transaction?.Commit();

            _transaction?.Dispose();
            _connection.Dispose();

            _connectionFactory.UnregisterConnection(_scopeTransaction);

            enlistment.Done();
        }
コード例 #12
0
ファイル: ExcuteImport.cs プロジェクト: BishopCheng/WbApi
        public int ExcuteNotQuery(string sqlStr, IList <List <DbParameter> > lstParmeters)
        {
            int           num           = 0;
            DbTransaction dbTransaction = null;
            DbConnection  dbConnection  = null;
            string        str           = "";

            try
            {
                dbConnection = providerFactory.CreateConnection();                          //利用链接工厂创建链接
                dbConnection.ConnectionString = connectionString;                           //给链接字符串赋值
                dbConnection.Open();                                                        //打开链接
                dbTransaction = dbConnection.BeginTransaction(IsolationLevel.Serializable); //开始事务
                int count = lstParmeters.Count;
                for (int i = 0; i < count; i++)
                {
                    DbCommand dbCommand = providerFactory.CreateCommand();
                    dbCommand.CommandText = sqlStr;
                    dbCommand.Connection  = dbConnection;
                    dbCommand.CommandType = CommandType.Text;
                    dbCommand.Transaction = dbTransaction;
                    str = sqlStr + ">>" + i;
                    if (lstParmeters[i] != null && lstParmeters[i].Count > 0)
                    {
                        dbCommand.Parameters.AddRange(lstParmeters[i].ToArray());
                    }
                    num += dbCommand.ExecuteNonQuery(); //保存下此刻执行完毕的条数,并添加到总数中
                    dbCommand.Parameters.Clear();       //清空参数
                }
                dbTransaction?.Commit();                //允许提交空事务
            }
            catch (Exception ex)
            {
                dbTransaction?.Rollback();
                throw new Exception(str + "执行错误!" + ex.Message + "");
            }
            finally
            {
                if (dbConnection != null && dbConnection.State == ConnectionState.Open)
                {
                    dbTransaction.Rollback();
                    dbTransaction.Dispose();
                    dbConnection.Close();
                    dbConnection.Dispose();
                }
            }
            return(num);
        }
コード例 #13
0
ファイル: ExcuteImport.cs プロジェクト: BishopCheng/WbApi
        public int ExcuteNotQuery(IList <string> lstSqls, IList <List <DbParameter> > lstParmeters)
        {
            DbTransaction dbTransaction = null;
            DbConnection  dbConnection  = null;
            int           num           = 0;
            string        str           = "";

            try {
                dbConnection = providerFactory.CreateConnection();
                dbConnection.ConnectionString = connectionString;
                dbConnection.Open();
                int count = lstParmeters.Count;
                dbTransaction = dbConnection.BeginTransaction(IsolationLevel.Serializable);
                for (int i = 0; i < count; i++)
                {
                    DbCommand dbCommand = providerFactory.CreateCommand();
                    dbCommand.CommandText    = lstSqls[i];
                    dbCommand.CommandTimeout = commandTimeOut;
                    dbCommand.Connection     = dbConnection;
                    str = lstSqls[i];
                    if (lstParmeters[i] != null && lstParmeters[i].Count > 0)
                    {
                        dbCommand.Parameters.AddRange(lstParmeters[i].ToArray());
                    }
                    num += dbCommand.ExecuteNonQuery();
                    dbCommand.Parameters.Clear();
                }
                dbTransaction?.Commit();
            }
            catch (Exception ex)
            {
                dbTransaction.Rollback();
                throw new Exception("'" + str + "'" + "执行错误!" + ex);
            }
            finally
            {
                dbTransaction.Dispose();
                dbConnection.Close();
                dbConnection.Dispose();
            }
            return(num);
        }
コード例 #14
0
ファイル: BaseRepository.cs プロジェクト: orenray/RaysBlog
        public bool DeleteEntitiy(T entity)
        {
            DbTransaction tran   = null;
            bool          result = false;

            using (var conn = ConnectionFactory.GetOpenConnection())
            {
                try
                {
                    tran   = conn.BeginTransaction();
                    result = conn.Delete(entity, transaction: tran);
                    tran?.Commit();
                }
                catch (Exception ex)
                {
                    tran?.Rollback();
                    result = false;
                    //throw new Exception(ex.Message);
                }
            }
            return(result);
        }
コード例 #15
0
        internal async Task <bool> ExecuteAsync(string sql, params object[] args)
        {
            using (var connection = await CreateConnectionAsync())
            {
                DbTransaction trans = transactions ? connection.BeginTransaction(IsolationLevel.ReadCommitted) : null;
                try
                {
                    using (var cmd = CreateSqlCommand(connection, trans, sql, args)) {
                        bool ret = await cmd.ExecuteNonQueryAsync() > 0;

                        trans?.Commit();

                        return(ret);
                    }
                }
                catch (Exception ex)
                {
                    Log.Message(LogTypes.Error, ex.ToString());
                    trans?.Rollback();
                    return(false);
                }
            }
        }
コード例 #16
0
 public void Commit()
 {
     _transaction?.Commit();
 }
コード例 #17
0
        internal void Commit()
        {
            TransactionInstance?.Commit();

            DisposeofTransaction();
        }
コード例 #18
0
        private async Task MigrateAsync(IReadOnlyCollection <IMigration> orderedMigrations, bool isUpgrade, MigrationPolicy policy, CancellationToken token = default)
        {
            if (policy == MigrationPolicy.Forbidden)
            {
                throw new MigrationException(MigrationError.PolicyError, $"{(isUpgrade ? "Upgrading": "Downgrading")} is forbidden due to migration policy");
            }

            if (orderedMigrations.Count == 0)
            {
                return;
            }

            var operationName = isUpgrade
                ? "Upgrade"
                : "Downgrade";

            foreach (var migration in orderedMigrations)
            {
                token.ThrowIfCancellationRequested();

                DbTransaction?transaction = null;

                try
                {
                    // sometimes transactions fails without reopening connection
                    //todo #19: fix it later
                    await _dbProvider.CloseConnectionAsync();

                    await _dbProvider.OpenConnectionAsync(token);

                    if (migration.IsTransactionRequired)
                    {
                        transaction = _dbProvider.BeginTransaction();
                    }
                    else
                    {
                        _logger?.LogWarning($"Transaction is disabled for migration {migration.Version}");
                    }

                    _logger?.LogInformation($"{operationName} to {migration.Version} ({migration.Comment} for database \"{_dbProvider.DbName}\")...");

                    if (isUpgrade)
                    {
                        await migration.UpgradeAsync(transaction, token);

                        await _dbProvider.SaveAppliedMigrationVersionAsync(migration.Comment, migration.Version, token);
                    }
                    else
                    {
                        if (!(migration is IDowngradeMigration downgradableMigration))
                        {
                            throw new MigrationException(MigrationError.MigrationNotFound, $"Migration with version {migration.Version} doesn't support downgrade");
                        }

                        await downgradableMigration.DowngradeAsync(transaction, token);

                        await _dbProvider.DeleteAppliedMigrationVersionAsync(migration.Version, token);
                    }

                    // Commit transaction if all commands succeed, transaction will auto-rollback
                    // when disposed if either commands fails
                    transaction?.Commit();

                    _logger?.LogInformation($"{operationName} to {migration.Version} (database \"{_dbProvider.DbName}\") completed.");
                }
                catch (Exception e)
                {
                    throw new MigrationException(
                              MigrationError.MigratingError,
                              $"Error while executing {operationName.ToLower()} migration to {migration.Version} for database \"{_dbProvider.DbName}\": {e.Message}",
                              e);
                }
                finally
                {
                    transaction?.Dispose();
                }
            }
        }
コード例 #19
0
 public void Commit()
 {
     _dbContextTransaction?.Commit();
     _dbTransaction?.Commit();
 }
 public void Commit(DbTransaction transaction)
 {
     transaction?.Commit();
 }
コード例 #21
0
 public void Commit() => DbTransaction?.Commit();
コード例 #22
0
 public virtual void Commit()
 {
     DbTransaction?.Commit();
 }
コード例 #23
0
ファイル: HDIC.cs プロジェクト: changchengxu/soc_nds_csharp
 public static int ExcuteNonQuery(DbTransaction trans, CommandType cmdType, string cmdText, params DbParameter[] cmdParms)
 {
     using (DbConnection conn = provider.CreateConnection())
     {
         using (DbCommand cmd = provider.CreateCommand())
         {
             try
             {
                 PrepareCommand(cmd, conn, trans, cmdType, cmdText, cmdParms);
                 //return cmd.ExecuteNonQuery();
                 int count = 0;               //长城添加
                 count = cmd.ExecuteNonQuery(); //长城添加
                 if (trans != null) { trans.Commit(); }           //长城添加
                 return count;                //长城添加
             }
             catch (Exception ex)
             {
                 if (trans != null) { trans.Rollback(); }//长城添加
                 conn.Close();
                 cmd.Dispose();
                 throw new Exception("数据操作错误" + ex.ToString());
             }
         }
     }
 }
コード例 #24
0
ファイル: DBHelper.cs プロジェクト: eyupgevenim/RentCar
 public void CommitTransaction()
 {
     transaction?.Commit();
     transaction = null;
 }
コード例 #25
0
        /// <summary>
        /// Apply changes : Insert / Updates Delete
        /// the fromScope is local client scope when this method is called from server
        /// the fromScope is server scope when this method is called from client
        /// </summary>
        public virtual async Task <(SyncContext, ChangesApplied)> ApplyChangesAsync(SyncContext context, ScopeInfo fromScope, BatchInfo changes)
        {
            ChangeApplicationAction changeApplicationAction;
            DbTransaction           applyTransaction = null;
            ChangesApplied          changesApplied   = new ChangesApplied();
            DbConnection            connection       = null;

            try
            {
                using (connection = this.CreateConnection())
                {
                    await connection.OpenAsync();

                    // Create a transaction
                    applyTransaction = connection.BeginTransaction();

                    // -----------------------------------------------------
                    // 0) Check if we are in a reinit mode
                    // -----------------------------------------------------
                    if (context.SyncWay == SyncWay.Download && context.SyncType != SyncType.Normal)
                    {
                        changeApplicationAction = this.ResetInternal(context, connection, applyTransaction, fromScope);

                        // Rollback
                        if (changeApplicationAction == ChangeApplicationAction.Rollback)
                        {
                            throw new SyncException("Rollback during reset tables", context.SyncStage, this.ProviderTypeName, SyncExceptionType.Rollback);
                        }
                    }

                    // -----------------------------------------------------
                    // 1) Applying deletes. Do not apply deletes if we are in a new database
                    // -----------------------------------------------------
                    if (!fromScope.IsNewScope)
                    {
                        changeApplicationAction = this.ApplyChangesInternal(context, connection, applyTransaction, fromScope, changes, DmRowState.Deleted, changesApplied);

                        // Rollback
                        if (changeApplicationAction == ChangeApplicationAction.Rollback)
                        {
                            throw new SyncException("Rollback during applying deletes", context.SyncStage, this.ProviderTypeName, SyncExceptionType.Rollback);
                        }
                    }

                    // -----------------------------------------------------
                    // 1) Applying Inserts
                    // -----------------------------------------------------
                    changeApplicationAction = this.ApplyChangesInternal(context, connection, applyTransaction, fromScope, changes, DmRowState.Added, changesApplied);

                    // Rollback
                    if (changeApplicationAction == ChangeApplicationAction.Rollback)
                    {
                        throw new SyncException("Rollback during applying inserts", context.SyncStage, this.ProviderTypeName, SyncExceptionType.Rollback);
                    }

                    // -----------------------------------------------------
                    // 1) Applying updates
                    // -----------------------------------------------------
                    changeApplicationAction = this.ApplyChangesInternal(context, connection, applyTransaction, fromScope, changes, DmRowState.Modified, changesApplied);

                    // Rollback
                    if (changeApplicationAction == ChangeApplicationAction.Rollback)
                    {
                        throw new SyncException("Rollback during applying updates", context.SyncStage, this.ProviderTypeName, SyncExceptionType.Rollback);
                    }

                    applyTransaction?.Commit();

                    return(context, changesApplied);
                }
            }
            catch (SyncException se)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SyncException(ex, SyncStage.TableChangesApplying, this.ProviderTypeName);
            }
            finally
            {
                if (applyTransaction != null)
                {
                    applyTransaction.Dispose();
                    applyTransaction = null;
                }

                if (connection != null && connection.State == ConnectionState.Open)
                {
                    connection.Close();
                }

                if (changes != null)
                {
                    changes.Clear();
                }
            }
        }
コード例 #26
0
ファイル: ObjectScopeExtensions.cs プロジェクト: MingLu8/Nemo
        public static bool Commit <T>(this T dataEntity)
            where T : class
        {
            var success = true;
            var context = ObjectScope.Current;

            if (context != null)
            {
                DbTransaction transaction = null;
                if (context.ChangeTracking == ChangeTrackingMode.Automatic)
                {
                    var connection             = context.Connection ?? DbFactory.CreateConnection(null, typeof(T), context.Configuration);
                    var externalConnection     = context.Connection != null;
                    var openConnectionRequired = !externalConnection || context.Connection.State != ConnectionState.Open;
                    try
                    {
                        if (openConnectionRequired)
                        {
                            connection.Open();
                        }
                        if (context.Transaction == null)
                        {
                            transaction = connection.BeginTransaction();
                        }

                        var changes   = CompareObjects(dataEntity, dataEntity.Old());
                        var statement = GetCommitStatement(changes, connection);
                        if (!string.IsNullOrEmpty(statement.Item1))
                        {
                            var response =
                                ObjectFactory.Execute <T>(new OperationRequest
                            {
                                Operation     = statement.Item1,
                                OperationType = OperationType.Sql,
                                Parameters    = statement.Item2,
                                Connection    = connection,
                                ReturnType    = OperationReturnType.SingleResult,
                                Transaction   = transaction,
                                Configuration = context.Configuration
                            });
                            success = response.Value != null;
                            if (success)
                            {
                                SetGeneratedPropertyValues(statement.Item3, (IDataReader)response.Value);
                            }
                        }

                        transaction?.Commit();
                    }
                    catch (Exception ex)
                    {
                        transaction?.Rollback();
                        throw;
                    }
                    finally
                    {
                        if (!externalConnection)
                        {
                            connection.Dispose();
                        }
                    }
                }
                else if (context.ChangeTracking == ChangeTrackingMode.Debug)
                {
                    var connection             = context.Connection ?? DbFactory.CreateConnection(null, typeof(T), context.Configuration);
                    var externalConnection     = context.Connection != null;
                    var openConnectionRequired = !externalConnection || context.Connection.State != ConnectionState.Open;
                    try
                    {
                        if (openConnectionRequired)
                        {
                            connection.Open();
                        }
                        if (context.Transaction == null)
                        {
                            transaction = connection.BeginTransaction();
                        }
                        var changes   = CompareObjects(dataEntity, dataEntity.Old());
                        var statement = GetCommitStatement(changes, connection);
                        Console.WriteLine(statement.Item1);

                        transaction?.Commit();
                    }
                    catch (Exception ex)
                    {
                        transaction?.Rollback();
                        throw;
                    }
                    finally
                    {
                        if (!externalConnection)
                        {
                            connection.Dispose();
                        }
                    }
                }

                if (context.IsNested)
                {
                    success = context.UpdateOuterSnapshot(dataEntity);
                }

                if (success)
                {
                    context.Cleanup();

                    context.Transaction?.Complete();
                }
            }

            return(success);
        }
コード例 #27
0
ファイル: BaseRepository.cs プロジェクト: tww19861004/fastSQL
 public virtual void Commit()
 {
     _transaction?.Commit();
     _transaction?.Dispose();
     _transaction = null;
 }
コード例 #28
0
 public virtual void CommitTransaction()
 {
     DbTransaction?.Commit();
     TransactionScope?.Complete();
     Dispose();
 }
コード例 #29
0
 /// <summary>
 /// 提交
 /// </summary>
 public void Commit()
 {
     _innerTransaction?.Commit();
 }
コード例 #30
0
ファイル: MySqlHelper.cs プロジェクト: kuibono/Voodoo-1
 /// <summary>
 /// 对连接执行 Transact-SQL 语句并返回受影响的行数
 /// </summary>
 /// <param name="CmdType">指定如何解释命令字符串</param>
 /// <param name="CmdText">Transact-SQL 语句</param>
 /// <param name="CmdParameters">SqlCommand 的参数</param>
 /// <param name="Transaction">Transact-SQL 事务</param>
 /// <returns>返回受影响的行数</returns>
 public int ExecuteNonQuery(CommandType CmdType, string CmdText, DbParameter[] CmdParameters, DbTransaction Transaction)
 {
     this.CreateCmd(CmdType, CmdText, CmdParameters, (MySqlTransaction)Transaction);
     int num2 = 0;
     if (Transaction != null)
     {
         try
         {
             num2 = this.Cmd.ExecuteNonQuery();
             Transaction.Commit();
         }
         catch (Exception exception1)
         {
             Exception exception = exception1;
             Transaction.Rollback();
         }
     }
     else
     {
         num2 = this.Cmd.ExecuteNonQuery();
     }
     this.Close();
     this.Dispose();
     return num2;
 }
コード例 #31
0
 internal virtual void Commit()
 {
     _transaction?.Commit();
 }
コード例 #32
0
 public void Commit()
 {
     _activeTransaction?.Commit();
     _activeTransaction = null;
 }