コード例 #1
0
        public void DoInTransaction(Action <IDbConnection> action)
        {
            using (var connection = _providerFactory.CreateConnection())
            {
                if (connection == null)
                {
                    throw new InvalidOperationException("Current connection is null.");
                }

                DbTransaction transaction = null;

                try
                {
                    connection.ConnectionString = _connectionString;
                    connection.Open();
                    transaction = connection.BeginTransaction();

                    _currentConnection  = connection;
                    _currentTransaction = transaction;

                    action(connection);

                    transaction.Commit();
                }
                catch
                {
                    transaction?.Rollback();
                    throw;
                }
                finally
                {
                    if (connection.State == ConnectionState.Open)
                    {
                        connection.Close();
                    }

                    _currentConnection  = null;
                    _currentTransaction = null;
                }
            }
        }
コード例 #2
0
        public static async Task UseAsync(
            this DbTransaction transaction,
            Action <DbTransaction> execute,
            CancellationToken cancellationToken = default)
        {
            Check.ArgNotNull(transaction, nameof(transaction));

            var  connection    = transaction.Connection;
            bool ownConnection = false;

            try
            {
                if (connection.State.HasFlag(ConnectionState.Closed))
                {
                    ownConnection = true;
                    await connection.OpenAsync(cancellationToken)
                    .ConfigureAwait(false);
                }

                var task = new Task(() => execute(transaction));
                task.Start();
                await task.ConfigureAwait(false);

                transaction.Commit();
            }
            catch
            {
                transaction?.Rollback();
                connection?.Close();
                throw;
            }
            finally
            {
                if (ownConnection)
                {
                    connection.Close();
                }
            }
        }
コード例 #3
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);
        }
コード例 #4
0
        /// <summary>
        /// Execute any non-DML SQL Query
        /// </summary>
        /// <param name="connectionString">Connection string to database</param>
        /// <param name="sql">Any SELECT SQL that you want to perform with/without parameterized parameters (Do not directly put sql parameter in this parameter)</param>
        /// <param name="parameters">SQL parameters according to the sql parameter</param>
        /// <param name="commandType">Type of SQL Command</param>
        /// <returns></returns>
        /// <exception cref="Exception"/>
        public static async Task <int> ExecuteNonQueryAsync <TDatabaseType>(string connectionString, string sql, IEnumerable <DbParameter> parameters = null, System.Data.CommandType commandType = System.Data.CommandType.Text)
            where TDatabaseType : DbConnection, new()
        {
            DbTransaction transaction = null;

            try
            {
                int result = -1;
                using (var connection = new TDatabaseType())
                {
                    connection.ConnectionString = connectionString;
                    await connection.OpenAsync();

                    transaction = connection.BeginTransaction();
                    using (var command = connection.CreateCommand())
                    {
                        command.CommandText = sql;
                        command.Transaction = transaction;
                        command.CommandType = commandType;
                        if (parameters != null)
                        {
                            foreach (var parameter in parameters)
                            {
                                command.Parameters.Add(parameter);
                            }
                        }
                        result = await command.ExecuteNonQueryAsync();
                    }
                    transaction.Commit();
                    connection.Close();
                }
                return(result);
            }
            catch (Exception e)
            {
                transaction?.Rollback();
                throw e;
            }
        }
コード例 #5
0
        /// <summary>
        /// Execute SELECT SQL query and return IEnumerable of specified POCO that is matching with the query columns
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="connectionString">Connection string to database</param>
        /// <param name="sql">Any SELECT SQL that you want to perform with/without parameterized parameters (Do not directly put sql parameter in this parameter)</param>
        /// <param name="parameters">SQL parameters according to the sql parameter</param>
        /// <param name="objectBuilder">How the POCO should build with each giving row of SqlDataReader</param>
        /// <param name="commandType">Type of SQL Command</param>
        /// <returns>IEnumerable of POCO</returns>
        /// <exception cref="Exception"/>
        public IEnumerable <T> ExecuteReader <T>(string sql, IEnumerable <DbParameter> parameters, Func <DbDataReader, T> objectBuilder, System.Data.CommandType commandType = System.Data.CommandType.Text)
            where T : class, new()
        {
            DbTransaction transaction = null;

            try
            {
                List <T> result = new List <T>();
                transaction = connection.BeginTransaction();
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = sql;
                    command.Transaction = transaction;
                    command.CommandType = commandType;
                    if (parameters != null)
                    {
                        foreach (var parameter in parameters)
                        {
                            command.Parameters.Add(parameter);
                        }
                    }
                    using (var cursor = command.ExecuteReader())
                    {
                        while (cursor.Read())
                        {
                            result.Add(objectBuilder(cursor));
                        }
                    }
                }
                transaction.Commit();
                return(result);
            }
            catch (Exception e)
            {
                transaction?.Rollback();
                throw e;
            }
        }
コード例 #6
0
        /// <summary>
        /// Execute SELECT SQL query and return IEnumerable of dynamic object
        /// </summary>
        /// <param name="connectionString">Connection string to database</param>
        /// <param name="sql">Any SELECT SQL that you want to perform with/without parameterized parameters (Do not directly put sql parameter in this parameter)</param>
        /// <param name="parameters">SQL parameters according to the sql parameter</param>
        /// <param name="commandType">Type of SQL Command</param>
        /// <returns>IEnumerable of dynamic object</returns>
        /// <exception cref="Exception"/>
        public async Task <IEnumerable <dynamic> > ExecuteReaderAsync(string sql, IEnumerable <DbParameter> parameters = null, System.Data.CommandType commandType = System.Data.CommandType.Text)
        {
            DbTransaction transaction = null;

            try
            {
                List <dynamic> result = new List <dynamic>();
                transaction = connection.BeginTransaction();
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = sql;
                    command.Transaction = transaction;
                    command.CommandType = commandType;
                    if (parameters != null)
                    {
                        foreach (var parameter in parameters)
                        {
                            command.Parameters.Add(parameter);
                        }
                    }
                    using (var cursor = await command.ExecuteReaderAsync())
                    {
                        var columns = Enumerable.Range(0, cursor.FieldCount).Select(cursor.GetName).ToList();
                        while (await cursor.ReadAsync())
                        {
                            result.Add(Data.RowBuilder(cursor, columns));
                        }
                    }
                }
                transaction.Commit();
                return(result);
            }
            catch (Exception e)
            {
                transaction?.Rollback();
                throw e;
            }
        }
コード例 #7
0
        /// <summary>
        /// Execute SELECT SQL query and return a scalar object
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="connectionString">Connection string to database</param>
        /// <param name="sql">Any SELECT SQL that you want to perform with/without parameterized parameters (Do not directly put sql parameter in this parameter)</param>
        /// <param name="parameters">SQL parameters according to the sql parameter</param>
        /// <param name="commandType">Type of SQL Command</param>
        /// <returns></returns>
        /// <exception cref="Exception"/>
        public static T ExecuteScalar <T, TDatabaseType>(string connectionString, string sql, IEnumerable <DbParameter> parameters = null, System.Data.CommandType commandType = System.Data.CommandType.Text)
            where TDatabaseType : DbConnection, new()
        {
            DbTransaction transaction = null;

            try
            {
                T result = default;
                using (var connection = new TDatabaseType())
                {
                    connection.ConnectionString = connectionString;
                    connection.Open();
                    transaction = connection.BeginTransaction();
                    using (var command = connection.CreateCommand())
                    {
                        command.CommandText = sql;
                        command.Transaction = transaction;
                        command.CommandType = commandType;
                        if (parameters != null)
                        {
                            foreach (var parameter in parameters)
                            {
                                command.Parameters.Add(parameter);
                            }
                        }
                        result = (T)command.ExecuteScalar();
                    }
                    transaction.Commit();
                    connection.Close();
                }
                return(result);
            }
            catch (Exception e)
            {
                transaction?.Rollback();
                throw e;
            }
        }
コード例 #8
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);
                }
            }
        }
コード例 #9
0
ファイル: DatabaseProxy.cs プロジェクト: spartajet/Testflow
        public virtual void DeleteTestInstance(string fileterString)
        {
            DbTransaction transaction = null;

            try
            {
                // 删除TestInstance需要执行事务流程
                transaction = Connection.BeginTransaction(IsolationLevel.Serializable);

                string deleteCmd = SqlCommandFactory.CreateDeleteCmd(DataBaseItemNames.StatusTableName, fileterString);
                ExecuteWriteCommand(deleteCmd, transaction);

                deleteCmd = SqlCommandFactory.CreateDeleteCmd(DataBaseItemNames.PerformanceTableName, fileterString);
                ExecuteWriteCommand(deleteCmd, transaction);

                deleteCmd = SqlCommandFactory.CreateDeleteCmd(DataBaseItemNames.SequenceTableName, fileterString);
                ExecuteWriteCommand(deleteCmd, transaction);

                deleteCmd = SqlCommandFactory.CreateDeleteCmd(DataBaseItemNames.SessionTableName, fileterString);
                ExecuteWriteCommand(deleteCmd, transaction);

                deleteCmd = SqlCommandFactory.CreateDeleteCmd(DataBaseItemNames.InstanceTableName, fileterString);
                ExecuteWriteCommand(deleteCmd, transaction);

                transaction.Commit();
            }
            catch (Exception)
            {
                transaction?.Rollback();
                throw;
            }
            finally
            {
                transaction?.Dispose();
            }
        }
コード例 #10
0
 public void RollBack()
 {
     _transaction?.Rollback();
 }
コード例 #11
0
 public void Rollback()
 {
     Transaction?.Rollback();
 }
コード例 #12
0
 public void Rollback()
 {
     _activeTransaction?.Rollback();
     _activeTransaction = null;
 }
コード例 #13
0
 public void Rollback() => DbTransaction?.Rollback();
コード例 #14
0
 /// <summary>
 /// 回滚
 /// </summary>
 public void Rollback()
 {
     _innerTransaction?.Rollback();
 }
コード例 #15
0
        public void InsertUser(User user)
        {
            using (var connection = _providerFactory.CreateConnection())
                using (var command = connection.CreateCommand())
                {
                    try
                    {
                        connection.ConnectionString = _connectionString;
                        connection.Open();

                        transaction = connection.BeginTransaction();

                        command.CommandText = $"insert into Users (Login,Password,PhoneNumber) values (@login, @password,@phoneNumber)";

                        var loginParameter = command.CreateParameter();
                        loginParameter.ParameterName = "@login";
                        loginParameter.DbType        = System.Data.DbType.String;
                        loginParameter.Value         = user.Login;



                        var passwordParameter = command.CreateParameter();
                        passwordParameter.ParameterName = "@password";
                        passwordParameter.DbType        = System.Data.DbType.String;
                        passwordParameter.Value         = user.Password;


                        var phoneNumberParameter = command.CreateParameter();
                        phoneNumberParameter.ParameterName = "@phoneNumber";
                        phoneNumberParameter.DbType        = System.Data.DbType.Int64;
                        phoneNumberParameter.Value         = user.PhoneNumber;

                        command.Parameters.Add(passwordParameter);
                        command.Parameters.Add(loginParameter);
                        command.Parameters.Add(phoneNumberParameter);

                        command.Transaction = transaction;


                        int affectedRows = command.ExecuteNonQuery();


                        if (affectedRows < 1)
                        {
                            throw new Exception("Вставка не удалась");
                        }
                        transaction.Commit();
                    }
                    catch (DbException exception)
                    {
                        //обработать
                        if (transaction != null)
                        {
                            transaction.Rollback();
                        }
                        throw;
                    }
                    catch (Exception exception)
                    {
                        //обработать
                        transaction?.Rollback();
                        throw;
                    }
                }
        }
コード例 #16
0
        public bool AddUser(string login, string password, string phoneNumber)
        {
            using (var connection = _providerFactory.CreateConnection())
                using (var command = connection.CreateCommand())

                {
                    DbTransaction transaction = null;

                    try
                    {
                        connection.ConnectionString = _connectionString;
                        connection.Open();
                        transaction = connection.BeginTransaction();

                        command.Transaction = transaction;

                        DbParameter loginParameter = command.CreateParameter();
                        loginParameter.ParameterName = "@login_param";
                        loginParameter.Value         = login;
                        loginParameter.DbType        = System.Data.DbType.String;
                        loginParameter.IsNullable    = true;

                        DbParameter passwordParameter = command.CreateParameter();
                        passwordParameter.ParameterName = "@password_param";
                        passwordParameter.Value         = password;
                        passwordParameter.DbType        = System.Data.DbType.String;
                        passwordParameter.IsNullable    = true;

                        DbParameter phonenumberParameter = command.CreateParameter();
                        phonenumberParameter.ParameterName = "@phonenumber_param";
                        phonenumberParameter.Value         = phoneNumber;
                        phonenumberParameter.DbType        = System.Data.DbType.String;
                        phonenumberParameter.IsNullable    = true;

                        command.Parameters.AddRange(new DbParameter[] { loginParameter, passwordParameter, phonenumberParameter });
                        command.CommandText = $"insert into users(Login, Password, PhoneNumber) values( @login_param, @password_param, @phonenumber_param)";

                        var affectRows = command.ExecuteNonQuery();
                        if (affectRows < 1)
                        {
                            throw new Exception("Обновление не было произведено");
                        }


                        transaction.Commit();
                        transaction.Dispose();
                        return(true); // true - без ошибок
                    }
                    catch (DbException exception)
                    {
                        transaction?.Rollback();
                        transaction.Dispose();
                        //throw;
                        return(false);
                    }
                    catch (Exception exception)
                    {
                        transaction?.Rollback();
                        transaction.Dispose();
                        //throw;
                        return(false);
                    }
                }
        }
コード例 #17
0
        public bool PayUpdate(User user, Calendar calendar, string cardNumber)
        {
            using (var connection = _providerFactory.CreateConnection())
                using (var command = connection.CreateCommand())

                {
                    DbTransaction transaction = null;

                    try
                    {
                        connection.ConnectionString = _connectionString;
                        connection.Open();
                        transaction = connection.BeginTransaction();

                        command.Transaction = transaction;

                        DbParameter rezervParameter = command.CreateParameter();
                        rezervParameter.ParameterName = "@cardnumber_param";
                        rezervParameter.Value         = cardNumber;
                        rezervParameter.DbType        = System.Data.DbType.String;
                        rezervParameter.IsNullable    = true;

                        DbParameter idParameter = command.CreateParameter();
                        idParameter.ParameterName = "@id_param";
                        idParameter.Value         = calendar.Id;
                        idParameter.DbType        = System.Data.DbType.Int32;
                        idParameter.IsNullable    = true;

                        DbParameter userIdParameter = command.CreateParameter();
                        userIdParameter.ParameterName = "@userid_param";
                        userIdParameter.Value         = user.Id;
                        userIdParameter.DbType        = System.Data.DbType.Int32;
                        userIdParameter.IsNullable    = true;

                        command.Parameters.AddRange(new DbParameter[] { rezervParameter, idParameter, userIdParameter });
                        command.CommandText = $"update Calendar set Pay = 1, UserId = @userid_param where Id = @id_param";
                        var affectRows = command.ExecuteNonQuery();
                        if (affectRows < 1)
                        {
                            throw new Exception("Обновление не было произведено");
                        }

                        command.CommandText = $"update Calendar set CardNumber = @cardNumber_param where Id = @id_param";
                        affectRows          = command.ExecuteNonQuery();
                        if (affectRows < 1)
                        {
                            throw new Exception("Обновление не было произведено");
                        }

                        transaction.Commit();
                        transaction.Dispose();
                        return(true); // true - без ошибок
                    }
                    catch (DbException exception)
                    {
                        transaction?.Rollback();
                        transaction.Dispose();
                        //throw;
                        return(false);
                    }
                    catch (Exception exception)
                    {
                        transaction?.Rollback();
                        transaction.Dispose();
                        //throw;
                        return(false);
                    }
                }
        }
コード例 #18
0
        public void InsertBasket(int choiceTypePizza, string loginUser)
        {
            using (var connection = _providerFactory.CreateConnection())
                using (var command = connection.CreateCommand())
                {
                    try
                    {
                        if (CheckIdMenuPizza(choiceTypePizza))
                        {
                            connection.ConnectionString = _connectionString;
                            connection.Open();

                            transaction         = connection.BeginTransaction();
                            command.CommandText = $"insert into Basket (idMenuPizza,idUsers) values (@idMenuPizza,@idUsers)";

                            var idMenuParameter = command.CreateParameter();
                            idMenuParameter.ParameterName = "@idMenuPizza";
                            idMenuParameter.DbType        = System.Data.DbType.Int64;
                            idMenuParameter.Value         = choiceTypePizza;


                            var idUsersParameter = command.CreateParameter();
                            idUsersParameter.ParameterName = "@idUsers";
                            idUsersParameter.DbType        = System.Data.DbType.Int64;
                            idUsersParameter.Value         = idUsers(loginUser);



                            command.Parameters.Add(idUsersParameter);
                            command.Parameters.Add(idMenuParameter);


                            command.Transaction = transaction;


                            int affectedRows = command.ExecuteNonQuery();


                            if (affectedRows < 1)
                            {
                                throw new Exception("Вставка не удалась");
                            }
                            Console.WriteLine("Добавлено в корзину");
                            transaction.Commit();
                        }
                    }
                    catch (DbException exception)
                    {
                        //обработать
                        if (transaction != null)
                        {
                            transaction.Rollback();
                        }
                        throw;
                    }
                    catch (Exception exception)
                    {
                        //обработать
                        transaction?.Rollback();
                        throw;
                    }
                }
        }
コード例 #19
0
ファイル: DapperDbContext.cs プロジェクト: war-man/YuebonCore
 /// <summary>
 /// 事务回滚
 /// </summary>
 public void RollBackTransaction()
 {
     DbTransaction?.Rollback();
     Committed = true;
     Dispose();
 }
コード例 #20
0
        public void Add(Order order)
        {
            using (var connection = _providerFactory.CreateConnection())
                using (var command = connection.CreateCommand())
                {
                    DbTransaction transaction = null;

                    try
                    {
                        connection.ConnectionString = _connectionString;
                        connection.Open();
                        transaction = connection.BeginTransaction();

                        command.Transaction = transaction;
                        command.CommandText = $"insert into [Order] values(@userId, @date, @totalSum, @status)";

                        DbParameter userIdParametr = command.CreateParameter();
                        userIdParametr.ParameterName = "@userId";
                        userIdParametr.DbType        = System.Data.DbType.Int32;
                        userIdParametr.Value         = order.UserId;

                        DbParameter dateParametr = command.CreateParameter();
                        dateParametr.ParameterName = "@date";
                        dateParametr.DbType        = System.Data.DbType.DateTime;
                        dateParametr.Value         = order.DateTime;

                        DbParameter totalSumParametr = command.CreateParameter();
                        totalSumParametr.ParameterName = "@totalSum";
                        totalSumParametr.DbType        = System.Data.DbType.Int32;
                        totalSumParametr.Value         = order.Sum;

                        DbParameter statusParametr = command.CreateParameter();
                        statusParametr.ParameterName = "@status";
                        statusParametr.DbType        = System.Data.DbType.Boolean;
                        statusParametr.Value         = order.State;

                        command.Parameters.AddRange(new DbParameter[] { userIdParametr, totalSumParametr, statusParametr, dateParametr });

                        var affectedRows = command.ExecuteNonQuery();

                        if (affectedRows < 1)
                        {
                            throw new Exception("Вставка не удалась.");
                        }

                        transaction.Commit();
                    }
                    catch (DbException exception)
                    {
                        Console.WriteLine($"Ошибка: {exception.Message}.");
                        transaction?.Rollback();
                        throw;
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine($"Ошибка: {exception.Message}.");
                        throw;
                    }
                    finally
                    {
                        transaction?.Dispose();
                    }
                }
        }
コード例 #21
0
ファイル: BaseRepository.cs プロジェクト: tww19861004/fastSQL
 public virtual void RollBack()
 {
     _transaction?.Rollback();
     _transaction?.Dispose();
     _transaction = null;
 }
 public void Rollback(DbTransaction transaction)
 {
     loggingService.LogMethodInvoked();
     transaction?.Rollback();
 }
コード例 #23
0
 public virtual void RollbackTransaction()
 {
     DbTransaction?.Rollback();
     Dispose();
 }
コード例 #24
0
        public void AddHotel(Hotels hotel)
        {
            using (var connection = _providerFactory.CreateConnection())
                using (var command = connection.CreateCommand())
                {
                    DbTransaction transaction = null;

                    try
                    {
                        connection.ConnectionString = _connectionString;
                        connection.Open();

                        transaction = connection.BeginTransaction();

                        command.CommandText = $"insert into Hotels values('{hotel.Name}', '{hotel.City}'  , '{hotel.Price}' ,  '{hotel.Star}')";
                        command.Transaction = transaction;

                        DbParameter nameParameter = command.CreateParameter();

                        nameParameter.ParameterName = "@name";
                        nameParameter.Value         = hotel.Name;

                        nameParameter.DbType     = System.Data.DbType.String;
                        nameParameter.IsNullable = false;

                        DbParameter cityParameter = command.CreateParameter();

                        cityParameter.ParameterName = "@city";
                        cityParameter.Value         = hotel.City;

                        cityParameter.DbType     = System.Data.DbType.String;
                        cityParameter.IsNullable = false;

                        DbParameter priceParameter = command.CreateParameter();

                        priceParameter.ParameterName = "@price";
                        priceParameter.Value         = hotel.Price;

                        priceParameter.DbType     = System.Data.DbType.Int64;
                        priceParameter.IsNullable = false;

                        DbParameter starParameter = command.CreateParameter();

                        starParameter.ParameterName = "@star";
                        starParameter.Value         = hotel.Star;

                        starParameter.DbType     = System.Data.DbType.String;
                        starParameter.IsNullable = false;

                        command.Parameters.AddRange(new DbParameter[] { nameParameter, cityParameter, priceParameter, starParameter });

                        var affectedRows = command.ExecuteNonQuery();

                        if (affectedRows < 1)
                        {
                            throw new Exception("Вставка не была произведена");
                        }
                        transaction.Commit();
                        transaction.Dispose();
                    }
                    catch (DbException exception)
                    {
                        transaction?.Rollback();
                        transaction.Dispose();
                        //TODO обработка ошибки
                        throw;
                    }
                    catch (Exception exception)
                    {
                        //TODO обработка ошибки
                        throw;
                    }
                }
        }
コード例 #25
0
ファイル: ObjectFactoryAsync.cs プロジェクト: MingLu8/Nemo
        public static async Task <long> InsertAsync <T>(IEnumerable <T> items, string connectionName = null, DbConnection connection = null, DbTransaction transaction = null, bool captureException = false, IConfiguration config = null)
            where T : class
        {
            var count = 0L;
            var connectionOpenedHere = false;
            var externalTransaction  = transaction != null;
            var externalConnection   = externalTransaction || connection != null;

            if (config == null)
            {
                config = ConfigurationFactory.Get <T>();
            }

            if (externalTransaction)
            {
                connection = transaction.Connection;
            }

            if (!externalConnection)
            {
                connection = DbFactory.CreateConnection(connectionName ?? config.DefaultConnectionName, config);
            }

            try
            {
                if (connection.State != ConnectionState.Open)
                {
                    connection.Open();
                    connectionOpenedHere = true;
                }
                if (transaction == null)
                {
                    transaction = connection.BeginTransaction();
                }

                var propertyMap = Reflector.GetPropertyMap <T>();
                var provider    = DialectFactory.GetProvider(transaction.Connection);

                var requests = BuildBatchInsert(items, transaction, captureException, propertyMap, provider, config);
                foreach (var request in requests)
                {
                    var response = await ExecuteAsync <T>(request).ConfigureAwait(false);

                    if (!response.HasErrors)
                    {
                        count += response.RecordsAffected;
                    }
                }
                transaction.Commit();

                return(count);
            }
            catch (Exception ex)
            {
                transaction?.Rollback();
                throw;
            }
            finally
            {
                if (connectionOpenedHere)
                {
                    connection.Clone();
                }

                if (!externalConnection)
                {
                    connection.Dispose();
                }
            }
        }
コード例 #26
0
        public void AddUser(User user)
        {
            using (var connection = _providerFactory.CreateConnection())
                using (var command = connection.CreateCommand())
                {
                    DbTransaction transaction = null;

                    try
                    {
                        connection.ConnectionString = _connectionString;
                        connection.Open();

                        transaction = connection.BeginTransaction();

                        command.CommandText = $"insert into Users values('{user.Login}', '{user.Password}'  , '{user.MobileNumber}' , '{user.Email}')";
                        command.Transaction = transaction;

                        DbParameter loginParameter = command.CreateParameter();

                        loginParameter.ParameterName = "@login";
                        loginParameter.Value         = user.Login;

                        loginParameter.DbType     = System.Data.DbType.String;
                        loginParameter.IsNullable = false;

                        DbParameter passwordParameter = command.CreateParameter();

                        passwordParameter.ParameterName = "@password";
                        passwordParameter.Value         = user.Password;

                        passwordParameter.DbType     = System.Data.DbType.String;
                        passwordParameter.IsNullable = false;


                        DbParameter mobileNumberParameter = command.CreateParameter();

                        mobileNumberParameter.ParameterName = "@mobileNumber";
                        mobileNumberParameter.Value         = user.MobileNumber;

                        mobileNumberParameter.DbType     = System.Data.DbType.String;
                        mobileNumberParameter.IsNullable = false;

                        command.Parameters.AddRange(new DbParameter[] { loginParameter, passwordParameter, mobileNumberParameter });

                        var affectedRows = command.ExecuteNonQuery();

                        if (affectedRows < 1)
                        {
                            throw new Exception("Вставка не была произведена");
                        }
                        transaction.Commit();
                        transaction.Dispose();
                    }
                    catch (DbException exception)
                    {
                        transaction?.Rollback();
                        transaction.Dispose();
                        //TODO обработка ошибки
                        throw;
                    }
                    catch (Exception exception)
                    {
                        //TODO обработка ошибки
                        throw;
                    }
                }
        }
コード例 #27
0
        ///<summary>
        /// Method Invocation of wrapper classes
        ///<summary>
        protected static FR_CAS_CGR_1400 Invoke(DbConnection connection, DbTransaction transaction, string connectionString, P_CAS_CGR_1400 parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            var cleanupConnection  = connection == null;
            var cleanupTransaction = transaction == null;

            var functionReturn = new FR_CAS_CGR_1400();

            try
            {
                if (cleanupConnection)
                {
                    connection = CSV2Core_MySQL.Support.DBSQLSupport.CreateConnection(connectionString);
                    connection.Open();
                }
                if (cleanupTransaction)
                {
                    transaction = connection.BeginTransaction();
                }

                functionReturn = Execute(connection, transaction, parameter, securityTicket);

                #region Cleanup Connection/Transaction
                //Commit the transaction
                if (cleanupTransaction)
                {
                    transaction.Commit();
                }
                //Close the connection
                if (cleanupConnection)
                {
                    connection.Close();
                }
                #endregion
            }
            catch (Exception ex)
            {
                try
                {
                    if (cleanupTransaction)
                    {
                        transaction?.Rollback();
                    }
                }
                catch
                {
                    // ignored
                }

                try
                {
                    if (cleanupConnection)
                    {
                        connection?.Close();
                    }
                }
                catch
                {
                    // ignored
                }

                throw new Exception("Exception occurred in method cls_Create_Report_for_All_Cases", ex);
            }
            return(functionReturn);
        }
コード例 #28
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());
             }
         }
     }
 }
コード例 #29
0
ファイル: DatabaseProxy.cs プロジェクト: spartajet/Testflow
        private void InitializeDatabaseAndConnection()
        {
            string testflowHome     = ConfigData.GetProperty <string>("TestflowHome");
            string databaseFilePath = ConfigData.GetProperty <string>("DatabaseName");

            // 使用DbProviderFactory方式连接需要在App.Config文件中定义DbProviderFactories节点
            // 但是App.Config文件只在入口Assembly中时才会被默认加载,所以目前写死为SqlConnection
//            Connection.ConnectionString = $"Data Source={databaseFilePath}";

            // 如果已经存在则直接跳出
            if (File.Exists(databaseFilePath))
            {
                Connection = new SQLiteConnection($"Data Source={databaseFilePath}");
                Connection.Open();
                return;
            }
            Connection = new SQLiteConnection($"Data Source={databaseFilePath}");
            DbTransaction transaction = null;

            try
            {
                const string endDelim      = ";";
                const string commentPrefix = "--";
                Connection.Open();
                string sqlFilePath =
                    $"{testflowHome}{CommonConst.DeployDir}{Path.DirectorySeparatorChar}{Constants.SqlFileName}";
                using (StreamReader reader = new StreamReader(sqlFilePath, Encoding.UTF8))
                {
                    StringBuilder createTableCmd = new StringBuilder(500);
                    string        lineData;
                    transaction = Connection.BeginTransaction(IsolationLevel.Serializable);
                    while (null != (lineData = reader.ReadLine()))
                    {
                        lineData = lineData.Trim();
                        if (lineData.StartsWith(commentPrefix))
                        {
                            continue;
                        }
                        createTableCmd.Append(lineData);
                        if (lineData.EndsWith(endDelim))
                        {
                            DbCommand dbCommand = Connection.CreateCommand();
                            dbCommand.CommandText = createTableCmd.ToString();
                            dbCommand.Transaction = transaction;
                            dbCommand.ExecuteNonQuery();
                            createTableCmd.Clear();
                        }
                    }
                    transaction.Commit();
                    transaction.Dispose();
                }
            }
            catch (Exception ex)
            {
                Logger.Print(LogLevel.Fatal, CommonConst.PlatformLogSession, ex, "Create database failed.");
                transaction?.Rollback();
                transaction?.Dispose();
                Connection?.Dispose();
                // 如果失败则删除文件
                File.Delete(databaseFilePath);
                throw;
            }
        }
コード例 #30
0
        internal void Rollback()
        {
            TransactionInstance?.Rollback();

            DisposeofTransaction();
        }
コード例 #31
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;
 }
コード例 #32
0
 public virtual void Rollback()
 {
     DbTransaction?.Rollback();
 }