public System.Data.SqlClient.SqlTransaction SaveTruck(GINTruckInfo truck, System.Data.SqlClient.SqlTransaction transaction) { IGINProcess originalGIN = new GINProcessBLL(currentGINProcess.GINProcessInformation.TransactionId); currentGINProcess.SaveTruck(truck, transaction); //ConfirmNoConcurrency(Truck, Load, Weight) var truckChanges = (from oTruck in originalGIN.GINProcessInformation.Trucks where oTruck.TruckId == truck.TruckId select new object[] { oTruck, truck, AuditTrailWrapper.ExistingRecord }); try { AuditTrailWrapper atw = new AuditTrailWrapper(AuditTrailWrapper.TruckRegistration, truckChanges.ToArray(), "GIN Process"); if (!atw.Save()) { transaction.Rollback(); throw new Exception("Failed to save audit trail!"); } } catch (Exception ex) { transaction.Rollback(); throw ex; } return(transaction); }
public System.Data.SqlClient.SqlTransaction SaveGIN(Guid truckId, System.Data.SqlClient.SqlTransaction transaction) { IGINProcess originalGIN = new GINProcessBLL(currentGINProcess.GINProcessInformation.TransactionId); currentGINProcess.SaveGIN(truckId, transaction); //ConfirmNoConcurrency(GIN) var ginChanges = (from oGIN in originalGIN.GINProcessInformation.Trucks join cGIN in currentGINProcess.GINProcessInformation.Trucks on oGIN.TruckId equals cGIN.TruckId where oGIN.TruckId == truckId select new object[] { oGIN, cGIN, AuditTrailWrapper.ExistingRecord }); try { AuditTrailWrapper atw = new AuditTrailWrapper(AuditTrailWrapper.TruckLoading, ginChanges.ToArray(), "GIN Process"); if (!atw.Save()) { transaction.Rollback(); throw new Exception("Failed to save audit trail!"); } } catch (Exception ex) { transaction.Rollback(); throw ex; } return(transaction); }
private void toolStripButtonSave_Click(object sender, EventArgs e) { string lsDealerNo = ""; Validate(); //Validate form so all data sets are updated with field values DealerbindingSource.EndEdit(); lsDealerNo = DEALERcomboBox.Text.ToString().Trim(); tableAdapConn = new System.Data.SqlClient.SqlConnection(); tableAdapConn.ConnectionString = IAC2018SQL.Properties.Settings.Default.IAC2010SQLConnectionString; tableAdapConn.Open(); dEALERTableAdapter.Connection = tableAdapConn; tableAdapTran = dEALERTableAdapter.BeginTransaction(); dEALERTableAdapter.Transaction = tableAdapTran; try { dEALERTableAdapter.Update(iacDataSet.DEALER.Rows[DealerbindingSource.Position]); tableAdapTran.Commit(); } catch (System.Data.SqlClient.SqlException ex) { tableAdapTran.Rollback(); MessageBox.Show("This is a Microsoft SQL Server database error: " + ex.Message.ToString()); } catch (System.InvalidOperationException ex) { tableAdapTran.Rollback(); MessageBox.Show("Invalid Operation Error: " + ex.Message.ToString()); } catch (Exception ex) { tableAdapTran.Rollback(); MessageBox.Show("General Exception Error: " + ex.Message.ToString()); } finally { dEALERTableAdapter.UnlockRecord(iacDataSet.DEALER.Rows[DealerbindingSource.Position].Field <String>("DEALER_ACC_NO")); tableAdapConn.Close(); tableAdapConn = null; tableAdapTran = null; toolStripButtonSave.Enabled = false; if (lbAddFlag) { lbAddFlag = false; iacDataSet.DEALER.Clear(); StartUpConfiguration(); } iacDataSet.AcceptChanges(); Program.gsKey = lsDealerNo; DEALERcomboBox.Text = lsDealerNo; if (lbEdit) { lbEdit = false; SetViewMode(); } } }
public void ExecuteSqlTran(Hashtable SQLStringList) { using (System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(this.connectionString)) { sqlConnection.Open(); using (System.Data.SqlClient.SqlTransaction sqlTransaction = sqlConnection.BeginTransaction()) { System.Data.SqlClient.SqlCommand sqlCommand = new System.Data.SqlClient.SqlCommand(); try { foreach (DictionaryEntry dictionaryEntry in SQLStringList) { string cmdText = dictionaryEntry.Key.ToString(); System.Data.SqlClient.SqlParameter[] cmdParms = (System.Data.SqlClient.SqlParameter[])dictionaryEntry.Value; DbHelperSQLP.PrepareCommand(sqlCommand, sqlConnection, sqlTransaction, cmdText, cmdParms); int num = sqlCommand.ExecuteNonQuery(); sqlCommand.Parameters.Clear(); } sqlTransaction.Commit(); } catch { sqlTransaction.Rollback(); throw; } } } }
public int ExecuteSqlTran(List <string> SQLStringList) { int result; using (System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(this.connectionString)) { sqlConnection.Open(); System.Data.SqlClient.SqlCommand sqlCommand = new System.Data.SqlClient.SqlCommand(); sqlCommand.Connection = sqlConnection; System.Data.SqlClient.SqlTransaction sqlTransaction = sqlConnection.BeginTransaction(); sqlCommand.Transaction = sqlTransaction; try { int num = 0; for (int i = 0; i < SQLStringList.Count; i++) { string text = SQLStringList[i]; if (text.Trim().Length > 1) { sqlCommand.CommandText = text; num += sqlCommand.ExecuteNonQuery(); } } sqlTransaction.Commit(); result = num; } catch { sqlTransaction.Rollback(); result = 0; } } return(result); }
public bool Guardar(System.Data.SqlClient.SqlTransaction transaccion) { /*using (SqlConnection conexion = new SqlConnection()) * { * SqlTransaction transaccion = null; * conexion.ConnectionString = Config.ConnectionString; * try * { * conexion.Open(); * transaccion = conexion.BeginTransaction();*/ foreach (GuiaComprobanteCobro comprobanteCobro in this.guiaComprobantesCobros) { if (!comprobanteCobro.Guardar(transaccion)) { transaccion.Rollback(); return(false); } } //transaccion.Commit(); return(true); /*} * catch (Exception ex) * { * transaccion.Rollback(); * throw ex; * } * }*/ }
public static bool ExecuteQueryTrans(string cmdtext, params SqlParameter[] parameters) { int i = 0; using (SqlConnection conn = new SqlConnection(connStr)) { System.Data.SqlClient.SqlCommand cm = new System.Data.SqlClient.SqlCommand(); cm.Connection = conn; conn.Open(); System.Data.SqlClient.SqlTransaction trans = conn.BeginTransaction(); try { cm.CommandText = cmdtext; cm.Parameters.AddRange(parameters); cm.Transaction = trans; i = cm.ExecuteNonQuery(); trans.Commit(); } catch { trans.Rollback(); } finally { conn.Close(); trans.Dispose(); conn.Dispose(); } } return(i > 0); }
public int DeleteCopy(LIB.CopyDTO copy, SqlTransaction trans) { bool isInScopeCreated = false; int rs; if (trans == null) { isInScopeCreated = true; trans = ConnectionManager.Con.BeginTransaction("CAT_CRE_TRANSACT"); } CopyDAO dao = new CopyDAO(); rs = dao.DeleteCopy(copy, trans); if (isInScopeCreated) { if (rs == 0) trans.Rollback(); else trans.Commit(); } return rs; }
public void ExecuteNonQuery(SqlCommand sqlCmd) { using (SqlConnection sqlConn = new SqlConnection()) { try { sqlConn.ConnectionString = strSqlConnectionString; if (sqlConn.State != ConnectionState.Open) { sqlConn.Open(); } sqlTrans = sqlConn.BeginTransaction("ExecuteNonQueryTransaction"); sqlCmd.Connection = sqlConn; sqlCmd.Transaction = sqlTrans; sqlCmd.ExecuteNonQuery(); sqlTrans.Commit(); } catch (SqlException exSql) { SqlException ex = exSql; try { if (sqlTrans != null) { sqlTrans.Rollback("ExecuteNonQueryTransaction"); } } catch (SqlException exRollback) { ex = exRollback; } throw ex; } } }
// /// <summary> // /// Método para dar de baja lógicamente a una zona de un tarifario. // /// </summary> // /// <returns>Retorna un booleano indicando el éxito de la operacion.</returns> // public bool Eliminar() // { // using (SqlConnection conexion = new SqlConnection()) // { // SqlTransaction transaccion = null; // conexion.ConnectionString = Config.ConnectionString; // // try // { // // conexion.Open(); // transaccion = conexion.BeginTransaction(); // Config.Conexion.EjecutarSinResultados(transaccion,"TarifarioFleteZonaDEL", this.TarifarioFleteZonaID); // //Se instancia un objeto de TarifarioFlete para por utilizar el metodo validar (Bety) // TarifarioFlete oTari= new TarifarioFlete(); // oTari.TarifarioFleteID=this.TarifarioFleteID; // oTari.ValidarTarifario(transaccion); // transaccion.Commit(); // return true; // } // catch(Exception) // { // transaccion.Rollback(); // return false; // } // } // } public bool Eliminar(int usuarioID, System.Data.SqlClient.SqlTransaction transaccion) { using (SqlConnection conexion = new SqlConnection()) { //SqlTransaction transaccion = null; conexion.ConnectionString = Config.ConnectionString; try { conexion.Open(); transaccion = conexion.BeginTransaction(); Config.Conexion.EjecutarSinResultados(transaccion, "TarifarioFleteZonaDEL", this.TarifarioFleteZonaID, usuarioID); //Se instancia un objeto de TarifarioFlete para por utilizar el metodo validar (Bety) TarifarioFlete oTari = new TarifarioFlete(); oTari.TarifarioFleteID = this.TarifarioFleteID; oTari.ValidarTarifario(transaccion); transaccion.Commit(); return(true); } catch (Exception) { transaccion.Rollback(); return(false); } } }
public void addunit() { tr = Conn.BeginTransaction(); try { sb = new StringBuilder(); sb.Append("INSERT INTO UNIT (UnitId,UnitName,UnitNameEng)"); sb.Append(" VALUES (@UnitId,@UnitName,@UnitNameEng)"); string sqlAdd; sqlAdd = sb.ToString(); com.CommandText = sqlAdd; com.CommandType = CommandType.Text; com.Connection = Conn; com.Transaction = tr; com.Parameters.Clear(); com.Parameters.Add("@UnitId", SqlDbType.NVarChar).Value = txtUnitId.Text.Trim(); com.Parameters.Add("@UnitName", SqlDbType.NVarChar).Value = txtUnitName.Text.Trim(); com.Parameters.Add("@UnitNameEng", SqlDbType.NVarChar).Value = txtUnitNameEng.Text.Trim(); com.ExecuteNonQuery(); tr.Commit(); } catch { MessageBox.Show("คุณป้อนรหัสหน่วยนับสินค้าซ้ำ !!!", "ผลการทำงาน", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); tr.Rollback(); } }
public static int InsertBySQL(List <string> SQL) { System.Data.SqlClient.SqlConnection oracleConnection = new System.Data.SqlClient.SqlConnection(constr); System.Data.SqlClient.SqlCommand oracleCommand = new System.Data.SqlClient.SqlCommand(); oracleCommand.Connection = oracleConnection; int rowsAffected = 0; oracleConnection.Open(); System.Data.SqlClient.SqlTransaction tran = oracleConnection.BeginTransaction(); try { foreach (string s in SQL) { oracleCommand.Transaction = tran; oracleCommand.CommandText = s; rowsAffected += oracleCommand.ExecuteNonQuery(); } tran.Commit(); } catch (Exception ex) { tran.Rollback(); throw new NotSupportedException(ex.Message); } finally { oracleConnection.Close(); } return(rowsAffected); }
/// <summary> /// Выполнение набора команд в одной транзакции /// </summary> /// <param name="commands">Список команд для выполнения</param> /// <param name="level">Уровень изоляции транзакции</param> /// <exception cref="System.ArgumentNullException"></exception> /// <exception cref="System.ArgumentException"></exception> /// <exception cref="System.InvalidOperationException"></exception> /// <exception cref="System.Data.SqlClient.SqlException"></exception> /// <exception cref="System.Exception"></exception> public void ExecuteTransaction(List <SqlCommand> commands, System.Data.IsolationLevel level = System.Data.IsolationLevel.RepeatableRead) { if (commands == null) { throw new ArgumentNullException("commands"); } System.Data.SqlClient.SqlTransaction transaction = null; try { connection.Open(); // Start a local transaction. transaction = connection.BeginTransaction(level); foreach (SqlCommand command in commands) { //command.Transaction = transaction; ExecuteTransaction(command, transaction); } // Attempt to commit the transaction. // connection.Close(); transaction.Commit(); } catch (SqlException ex) { // Attempt to roll back the transaction. transaction.Rollback(); throw ex; } finally { connection.Close(); } }
public void Perform(SqlTransaction transaction, SqlProjectInfo project, CommandAdder commandAdder) { var criticalError = false; try { using (var command = transaction.Connection.CreateCommand()) { command.CommandText = Entity.Content; command.Transaction = transaction; command.ExecuteNonQuery(); } Logger.Log("created {0}", Entity); } catch (Exception ex) { criticalError = true; Logger.Log("failed while trying to create {0}", Entity); Logger.Log(ex); transaction.Rollback(); } finally { if (!criticalError) { // command to update memory data must be performed only after sql commands commandAdder(new LambdaCommand((_, proj, _a) => UpdateProjectInfo(proj))); } } }
private void toolStripButtonDelete_Click(object sender, EventArgs e) { string lsDealerNo = ""; Validate(); //Validate form so all data sets are updated with field values lsDealerNo = DEALERcomboBox.Text.ToString().Trim(); tableAdapConn = new System.Data.SqlClient.SqlConnection(); tableAdapConn.ConnectionString = IAC2018SQL.Properties.Settings.Default.IAC2010SQLConnectionString; tableAdapConn.Open(); dEALERTableAdapter.Connection = tableAdapConn; tableAdapTran = dEALERTableAdapter.BeginTransaction(); dEALERTableAdapter.Transaction = tableAdapTran; try { dEALERTableAdapter.DeleteQuery(lsDealerNo); tableAdapTran.Commit(); } catch (System.Data.SqlClient.SqlException ex) { tableAdapTran.Rollback(); MessageBox.Show("The has been a Microsoft SQL Server Database Error: " + ex.Message.ToString()); } catch (System.InvalidOperationException ex) { tableAdapTran.Rollback(); MessageBox.Show("Invalid Operation Error: " + ex.Message.ToString()); } catch (System.Exception ex) { tableAdapTran.Rollback(); MessageBox.Show("General Exception Error: " + ex.Message.ToString()); } finally { iacDataSet.AcceptChanges(); tableAdapConn.Close(); tableAdapConn = null; tableAdapTran = null; toolStripButtonDelete.Enabled = false; toolStripButtonEdit.Enabled = false; iacDataSet.DEALER.Clear(); Program.gsKey = null; StartUpConfiguration(); } }
public int CreatePaySalary(PaySalary newPaySalary) { int result = -1; try { conn = db.openConn(); tr = conn.BeginTransaction(); sb = new StringBuilder(); sb.Remove(0, sb.Length); sb.Append("INSERT INTO tbPaySalary(payID,psnCode,payStartDate,payEndDate,period,salary,revenceAll,netIncome,total,pSalary,pOt,pWork,ppSo,psLa,psLast,psLess,psReam,psIns,psPenalty)"); sb.Append(" VALUES (@payID,@psnCode,@payStartDate,@payEndDate,@period,@salary,@revenceAll,@netIncome,@total,@pSalary,@pOt,@pWork,@ppSo,@psLa,@psLast,@psLess,@psReam,@psIns,@psPenalty)"); string sqlsave; sqlsave = sb.ToString(); comm = new SqlCommand(); comm.Connection = conn; comm.Transaction = tr; comm.CommandText = sqlsave; comm.Parameters.Clear(); comm.Parameters.Add("@payID", SqlDbType.NVarChar).Value = newPaySalary.payID; comm.Parameters.Add("@psnCode", SqlDbType.NVarChar).Value = newPaySalary.psnCode; comm.Parameters.Add("@payStartDate", SqlDbType.NVarChar).Value = newPaySalary.payStartDate; comm.Parameters.Add("@payEndDate", SqlDbType.NVarChar).Value = newPaySalary.payEndDate; comm.Parameters.Add("@period", SqlDbType.NVarChar).Value = newPaySalary.period; comm.Parameters.Add("@salary", SqlDbType.NVarChar).Value = newPaySalary.salary; comm.Parameters.Add("@revenceAll", SqlDbType.NVarChar).Value = newPaySalary.revenceAll; comm.Parameters.Add("@netIncome", SqlDbType.NVarChar).Value = newPaySalary.netIncome; comm.Parameters.Add("@total", SqlDbType.NVarChar).Value = newPaySalary.total; comm.Parameters.Add("@pSalary", SqlDbType.NVarChar).Value = newPaySalary.pSalary; comm.Parameters.Add("@pOt", SqlDbType.NVarChar).Value = newPaySalary.pOt; comm.Parameters.Add("@pWork", SqlDbType.NVarChar).Value = newPaySalary.pWork; comm.Parameters.Add("@ppSo", SqlDbType.NVarChar).Value = newPaySalary.ppSo; comm.Parameters.Add("@psLa", SqlDbType.NVarChar).Value = newPaySalary.psLa; comm.Parameters.Add("@psLast", SqlDbType.NVarChar).Value = newPaySalary.psLast; comm.Parameters.Add("@psLess", SqlDbType.NVarChar).Value = newPaySalary.psLess; comm.Parameters.Add("@psReam", SqlDbType.NVarChar).Value = newPaySalary.psReam; comm.Parameters.Add("@psIns", SqlDbType.NVarChar).Value = newPaySalary.psIns; comm.Parameters.Add("@psPenalty", SqlDbType.NVarChar).Value = newPaySalary.psPenalty; comm.ExecuteNonQuery(); tr.Commit(); result = 1; } catch (Exception ex) { tr.Rollback(); conn.Close(); return result; throw ex; } finally { conn.Close(); } return result; }
public static DataSet ExecuteDataset(SqlCommand command, SqlConnection connection, SqlTransaction transaction) { bool mustCloseConnection = false; #region Check if (connection == null) throw new ArgumentNullException("connection"); if (command == null) throw new ArgumentNullException("command"); if (connection.State != ConnectionState.Open) { mustCloseConnection = true; connection.Open(); } else { mustCloseConnection = false; } if (transaction != null) { if (transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); command.Transaction = transaction; } #endregion command.Connection = connection; command.Transaction = transaction; using (SqlDataAdapter da = new SqlDataAdapter(command)) { DataSet retval = new DataSet(); if (transaction == null) { da.Fill(retval); } else { try { da.Fill(retval); transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); throw ex; } } if (mustCloseConnection) connection.Close(); return retval; } }
public DataTable ReadEMPTable() { ThrowIfDisposed(); DataTable ds = new DataTable(); try { //クエリーの生成 SqlCommand sqlCom = new SqlCommand(); //クエリー送信先及びトランザクションの指定 sqlCom.Connection = this.sqlConn; sqlCom.Transaction = this.sqlTran; sqlCom.CommandText = "SELECT * FROM EMP_MASTER left outer join EMP_POST_MASTER on EMP_POST = EMP_POST_ID"; SqlDataAdapter sqlAda = new SqlDataAdapter(); sqlAda.SelectCommand = sqlCom; sqlAda.Fill(ds); }catch (Exception ex) { MessageBox.Show("データベース読み取りエラー " + ex.Message, "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error); sqlTran.Rollback(); sqlTran.Dispose(); sqlConn.Close(); sqlConn.Dispose(); Application.Exit(); } ds.PrimaryKey = new DataColumn[] { ds.Columns["EMP_CODE"] }; return(ds); }
public void Rollback() { if (myTrans != null) { myTrans.Rollback(); myTrans = null; CloseCon(); } }
public static void RollbackTransaction() { Transaction.Rollback(); Transaction = null; if (Connection.State == ConnectionState.Open) { Connection.Close(); } }
/// <summary> /// ロールバック /// </summary> /// <remarks></remarks> public void Rollback() { if (_trans != null) { _trans.Rollback(); _logger.Info("Rollback:" + _trans.ToString()); _trans = null; } }
public returnval merge(returnval val) { if (val.rows == null && val.childs == null) { SD.DataTable DataTable; using (SDSc.SqlConnection SqlConnection = new SDSc.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["moodleConnectionString1"].ConnectionString)) { DataTable = new SD.DataTable(); (new SDSc.SqlDataAdapter(new SDSc.SqlCommand() { CommandText = string.Format( "SELECT {0}{1}{2};" , selectcols.Replace("@currentuser", "1") , dbname == null ? "" : string.Format(" FROM {0}", dbname) , whereparam == null ? "" : string.Format(" WHERE {0}", whereparam .Replace("@currentuser", "1") .Replace("@currentlogin", "1")) ), Connection = SqlConnection })).Fill(DataTable); }; val.rows = new List <object[]>(); foreach (SD.DataRow DataRow in DataTable.Rows) { val.rows.Add(DataRow.ItemArray); } } else { using (SDSc.SqlConnection SqlConnection = new SDSc.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["moodleConnectionString1"].ConnectionString)) { SqlConnection.Open(); SDSc.SqlTransaction SqlTransaction = SqlConnection.BeginTransaction(); try { merge(val, SqlTransaction); if (val.childs != null) { foreach (returnval subtable in val.childs) { thistables.table(subtable.name).merge(subtable, SqlTransaction); if (subtable.childs != null) { foreach (returnval subtable2 in subtable.childs) { thistables.table(subtable2.name).merge(subtable2, SqlTransaction); } } } } SqlTransaction.Commit(); } catch (Exception e) { SqlTransaction.Rollback(); throw e; } } } return(val); }
public int CreateLabel(Label newLabel) { int result = -1; try { conn = db.openConn(); tr = conn.BeginTransaction(); sb = new StringBuilder(); sb.Remove(0, sb.Length); sb.Append("INSERT INTO Label(Id,PartName,SerialNo,PrintTime,Line,Ckt,Model,OilType,OilWeight,Status,Run,MM)"); sb.Append(" VALUES (@Id,@PartName,@SerialNo,@PrintTime,@Line,@Ckt,@Model,@OilType,@OilWeight,@Status,@Run,@MM)"); string sqlsave; sqlsave = sb.ToString(); comm = new SqlCommand(); comm.Connection = conn; comm.Transaction = tr; comm.CommandText = sqlsave; comm.Parameters.Clear(); comm.Parameters.Add("@Id", SqlDbType.NVarChar).Value = newLabel.Id; comm.Parameters.Add("@PartName", SqlDbType.NVarChar).Value = newLabel.PartName; comm.Parameters.Add("@SerialNo", SqlDbType.NVarChar).Value = newLabel.SerialNo; comm.Parameters.Add("@PrintTime", SqlDbType.DateTime).Value =newLabel.PrintTime; comm.Parameters.Add("@Line", SqlDbType.NVarChar).Value = newLabel.Line; comm.Parameters.Add("@Ckt", SqlDbType.NVarChar).Value = newLabel.Ckt; comm.Parameters.Add("@Model", SqlDbType.NVarChar).Value = newLabel.Model; comm.Parameters.Add("@OilType", SqlDbType.NVarChar).Value = newLabel.OilType; comm.Parameters.Add("@OilWeight", SqlDbType.NVarChar).Value = newLabel.OilWeight; comm.Parameters.Add("@Status", SqlDbType.NVarChar).Value = newLabel.Status; comm.Parameters.Add("@Run", SqlDbType.NVarChar).Value = newLabel.Run; comm.Parameters.Add("@MM", SqlDbType.NVarChar).Value = newLabel.MM; comm.ExecuteNonQuery(); tr.Commit(); logger.Fatal(" Save Complate "); result = 1; } catch (Exception ex) { logger.Fatal(" Save Not complate "+ex.Message); tr.Rollback(); conn.Close(); return result; throw ex; } finally { conn.Close(); } return result; }
/// <summary>執行 Transaction</summary> /// <param name="listSQL">欲執行交易的 ArrayList (內含 SQL 指令)</param> /// <param name="sqlConn">連線物件</param> /// <returns>Transaction是否成功</returns> /// <remarks></remarks> public static bool raiseTransaction(ArrayList listSQL, System.Data.SqlClient.SqlConnection sqlConn) { if (listSQL == null) { return(true); } if (listSQL.Count == 0) { return(true); } if (sqlConn == null) { sqlConn = createConnection(); } System.Data.SqlClient.SqlTransaction sqlTrans = null; if (!(sqlConn.State == ConnectionState.Open)) { sqlConn.Open(); } System.Data.SqlClient.SqlCommand cmd = sqlConn.CreateCommand(); StringBuilder strSQL = new StringBuilder(""); sqlTrans = sqlConn.BeginTransaction(); try { cmd.Transaction = sqlTrans; for (int i = 0; i <= listSQL.Count - 1; i++) { if (!string.IsNullOrEmpty(listSQL[i].ToString())) { strSQL.AppendLine(listSQL[i].ToString()); } } cmd.CommandText = strSQL.ToString(); cmd.ExecuteNonQuery(); sqlTrans.Commit(); return(true); } catch (Exception Ex) { if ((sqlTrans != null)) { sqlTrans.Rollback(); } //Message.alertMessage("C0002", null, Ex.Message.ToString(), null); return(false); } finally { if (!(sqlConn.State == ConnectionState.Closed)) { sqlConn.Close(); } } }
/// <summary> /// Método para dar de alta o modificar una cuenta cte de cliente. /// Define una transacción para ejecutar sus métodos y salvaguardar la integridad de /// los datos de la cuenta corriente y su detalle. Si no se puede grabar un movimiento /// se hace un rollback de la transacción. /// Invoca al stored procedure CuentaCorrienteClienteUPD en el que se encuentra la lógica /// que permite dar de alta una nueva cuenta corriente de cliente ó actualizar los datos /// de la cuenta corriente de cliente que se pasa como parámetro según corresponda. /// </summary> /// <returns>Retorna un booleano indicando si la operación se realizó con éxito.</returns> public bool Guardar(System.Data.SqlClient.SqlTransaction transaccion, IUsuarios usuario) { //using (SqlConnection conexion = new SqlConnection()) //{ // SqlTransaction transaccion = null; // conexion.ConnectionString = Config.ConnectionString; try { // conexion.Open(); // transaccion = conexion.BeginTransaction(); //transaccion Config.Conexion.EjecutarSinResultados(transaccion, "CuentaCorrienteClienteUPD", this.Cliente.ClienteID, this.CuentaCorrienteNro, Utiles.BaseDatos.FechaToSql(this.FechaSolicitud), Utiles.BaseDatos.DoubleToSql(this.ImporteSaldo), this.LimiteCredito, this.BloquearPorSistema, (int)this.EstadoCtaCte); if (!this.GuardarHistorico(transaccion, usuario)) { transaccion.Rollback(); return(false); } if (this.MovimientosCtasCtesClientesCol.getCount() > 0) { if (!this.MovimientosCtasCtesClientesCol.Guardar(transaccion)) { transaccion.Rollback(); return(false); } } //transaccion.Commit(); return(true); } catch (Exception ex) { //transaccion.Rollback(); string a = ex.Message; return(false); } // } }
public void CloseInsertConnectionWithTransaction(bool TrnsOk) { if (TrnsOk) { InsertTransaction.Commit(); } else { InsertTransaction.Rollback(); } InsertConnection.Close(); }
public int DeleteCatalogue(CatalogueDTO catalogue, SqlTransaction trans) { CatalogueDAO dao = new CatalogueDAO(); CopyBUS copyBus = new CopyBUS(); bool isInScopeCreated = false; int rs = 1; if (trans == null) { isInScopeCreated = true; trans = ConnectionManager.Con.BeginTransaction("CAT_DEL_TRANSACT"); } List<CopyDTO> list = copyBus.GetCopyByISBN(catalogue.ISBN); foreach (CopyDTO copyDTO in list) { rs = rs & copyBus.DeleteCopy(copyDTO, trans); if (rs == 0) break; } if (rs == 0) { if (isInScopeCreated) trans.Rollback(); } else { rs = rs & dao.DeleteCatalogue(catalogue, trans); if (isInScopeCreated) if (rs == 0) trans.Rollback(); else trans.Commit(); } return rs; }
public int CreateFinishingLabel(FinshingLabel newFinshingLabel) { int result = -1; try { conn = db.openConn(); tr = conn.BeginTransaction(); sb = new StringBuilder(); sb.Remove(0, sb.Length); sb.Append("INSERT INTO finishing_labels(barcode,complete_no,rev,place_name,product_barcode_date,product_text_date,line,shift,serial,print_date,user_create_name,status)"); sb.Append(" VALUES (@barcode,@complete_no,@rev,@place_name,@product_barcode_date,@product_text_date,@line,@shift,@serial,@print_date,@user_create_name,@status)"); string sqlsave; sqlsave = sb.ToString(); comm = new SqlCommand(); comm.Connection = conn; comm.Transaction = tr; comm.CommandText = sqlsave; comm.Parameters.Clear(); comm.Parameters.Add("@barcode", SqlDbType.NVarChar).Value = newFinshingLabel.Barcode; comm.Parameters.Add("@complete_no", SqlDbType.NVarChar).Value = newFinshingLabel.CompleteNo; comm.Parameters.Add("@rev", SqlDbType.NVarChar).Value = newFinshingLabel.Rev; comm.Parameters.Add("@place_name", SqlDbType.NVarChar).Value = newFinshingLabel.PlaceName; comm.Parameters.Add("@product_barcode_date", SqlDbType.NVarChar).Value = newFinshingLabel.ProductBarCodeDate; comm.Parameters.Add("@product_text_date", SqlDbType.NVarChar).Value = newFinshingLabel.ProductTextDate; comm.Parameters.Add("@line", SqlDbType.NVarChar).Value = newFinshingLabel.Line; comm.Parameters.Add("@shift", SqlDbType.NVarChar).Value = newFinshingLabel.Shift; comm.Parameters.Add("@serial", SqlDbType.NVarChar).Value = newFinshingLabel.Serial; comm.Parameters.Add("@print_date", SqlDbType.DateTime).Value = newFinshingLabel.PrintDate; comm.Parameters.Add("@user_create_name", SqlDbType.NVarChar).Value = newFinshingLabel.UserCreateName; comm.Parameters.Add("@status", SqlDbType.NVarChar).Value = newFinshingLabel.Status ; comm.ExecuteNonQuery(); tr.Commit(); result = 1; } catch (Exception ex) { tr.Rollback(); conn.Close(); return result; throw ex; } finally { conn.Close(); } return result; }
public int CreateMillin(Millin newMillin) { int result = -1; try { conn = db.openConn(); tr = conn.BeginTransaction(); sb = new StringBuilder(); sb.Remove(0, sb.Length); sb.Append("INSERT INTO tbMillin(psnCode,cause,mFormat,note,mdateStart,mhurStart,mdateEnd,mhurEnd,mdateAll,mhurAll,mless,mtime)"); sb.Append(" VALUES (@psnCode,@cause,@mFormat,@note,@mdateStart,@mhurStart,@mdateEnd,@mhurEnd,@mdateAll,@mhurAll,@mless,@mtime)"); string sqlsave; sqlsave = sb.ToString(); comm = new SqlCommand(); comm.Connection = conn; comm.Transaction = tr; comm.CommandText = sqlsave; comm.Parameters.Clear(); comm.Parameters.Add("@psnCode", SqlDbType.NVarChar).Value = newMillin.psnCode; comm.Parameters.Add("@cause", SqlDbType.NVarChar).Value = newMillin.cause; comm.Parameters.Add("@mFormat", SqlDbType.NVarChar).Value = newMillin.mFormat; comm.Parameters.Add("@note", SqlDbType.NVarChar).Value = newMillin.note; comm.Parameters.Add("@mdateStart", SqlDbType.NVarChar).Value = newMillin.mdateStart; comm.Parameters.Add("@mhurStart", SqlDbType.NVarChar).Value = newMillin.mhurStart; comm.Parameters.Add("@mdateEnd", SqlDbType.NVarChar).Value = newMillin.mdateEnd; comm.Parameters.Add("@mhurEnd", SqlDbType.NVarChar).Value = newMillin.mhurEnd; comm.Parameters.Add("@mdateAll", SqlDbType.NVarChar).Value = newMillin.mdateAll; comm.Parameters.Add("@mhurAll", SqlDbType.NVarChar).Value = newMillin.mhurAll; comm.Parameters.Add("@mless", SqlDbType.NVarChar).Value = newMillin.mless; comm.Parameters.Add("@mtime", SqlDbType.NVarChar).Value = newMillin.mtime; comm.ExecuteNonQuery(); tr.Commit(); result = 1; } catch (Exception ex) { tr.Rollback(); conn.Close(); return result; throw ex; } finally { conn.Close(); } return result; }
public int CreatePringtingLabel(PrintingLabels newPrintingLabels) { int result = -1; try { conn = db.openConn(); tr = conn.BeginTransaction(); sb = new StringBuilder(); sb.Remove(0, sb.Length); sb.Append("INSERT INTO printing_labels(barcode,part,product_date,serial,shift,rev,color_no,process,mold_no,user_create_name,create_date,status)"); sb.Append(" VALUES (@barcode,@part,@product_date,@serial,@shift,@rev,@color_no,@process,@mold_no,@user_create_name,@create_date,@status)"); string sqlsave; sqlsave = sb.ToString(); comm = new SqlCommand(); comm.Connection = conn; comm.Transaction = tr; comm.CommandText = sqlsave; comm.Parameters.Clear(); comm.Parameters.Add("@barcode", SqlDbType.NVarChar).Value = newPrintingLabels.BarCode; comm.Parameters.Add("@part", SqlDbType.NVarChar).Value = newPrintingLabels.Part; comm.Parameters.Add("@product_date", SqlDbType.NVarChar).Value = newPrintingLabels.ProductDate; comm.Parameters.Add("@serial", SqlDbType.NVarChar).Value = newPrintingLabels.Serial; comm.Parameters.Add("@shift", SqlDbType.NVarChar).Value = newPrintingLabels.Shift; comm.Parameters.Add("@rev", SqlDbType.NVarChar).Value = newPrintingLabels.Rev; comm.Parameters.Add("@color_no", SqlDbType.NVarChar).Value = newPrintingLabels.ColorNo; comm.Parameters.Add("@process", SqlDbType.NVarChar).Value = newPrintingLabels.Process; comm.Parameters.Add("@mold_no", SqlDbType.NVarChar).Value = newPrintingLabels.Mold; comm.Parameters.Add("@user_create_name", SqlDbType.NVarChar).Value = newPrintingLabels.UserCreateName; comm.Parameters.Add("@create_date", SqlDbType.DateTime).Value = newPrintingLabels.CreateDate; comm.Parameters.Add("@status", SqlDbType.NVarChar).Value = newPrintingLabels.Status; comm.ExecuteNonQuery(); tr.Commit(); result = 1; } catch (Exception ex) { tr.Rollback(); conn.Close(); return result; throw ex; } finally { conn.Close(); } return result; }
public void deletesupplier() { if (MessageBox.Show("คุณต้องการลบผู้ขาย ใช่หรือไม่?", "คำยืนยัน", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes) { tr = Conn.BeginTransaction(); try { sb = new StringBuilder(); sb.Append("DELETE SUPPLIER"); sb.Append(" WHERE (SupplierId=@SupplierId)"); string sqlDelete; sqlDelete = sb.ToString(); com.CommandText = sqlDelete; com.CommandType = CommandType.Text; com.Connection = Conn; com.Transaction = tr; com.Parameters.Clear(); com.Parameters.Add("@SupplierId", SqlDbType.NVarChar).Value = txtSupplierID.Text.Trim(); int result; result = com.ExecuteNonQuery(); if (result == 0) { tr.Rollback(); MessageBox.Show("ข้อมูลที่ต้องการลบไม่ถูกต้อง !!!", "ผลการทำงาน", MessageBoxButtons.OK, MessageBoxIcon.Information); txtSupplierID.SelectAll(); } else { tr.Commit(); //MessageBox.Show("ลบชื่อหน่วยนับสินค้า เรียบร้อยแล้ว !!!", "ผลการทำงาน", MessageBoxButtons.OK, MessageBoxIcon.Information); // ClearAllData();//Clear ข้อมูลจาก textbox ShowData(); FormatDgvSupplierList(); btnAdd.Enabled = true; btnEdit.Enabled = false; btnDelete.Enabled = false; } } catch (Exception ex) { tr.Rollback(); MessageBox.Show("เกิดข้อผิดพลาด เนื่องจาก " + ex.Message, "ผลการทำงาน", MessageBoxButtons.OK, MessageBoxIcon.Information); } } }
public string ClearAllUploadedFeeByZyh(int zyh) { string hr = string.Empty; StringBuilder sb = null; int iHr = 0; System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(GSettings.HisConnStr); DCCbhisDataContext hisDb = new DCCbhisDataContext(conn); System.Data.SqlClient.SqlTransaction trans = null; try { var _NhPersonInfo = GetNhPersonInfoByZyh(zyh); if (_NhPersonInfo == null) { throw new Exception("获取农合患者信息错误!"); } sb = new StringBuilder(256); iHr = NhLocalWrap.DeleteFeeList( string.Format("{0}$${1}", _NhPersonInfo.OrganCode, _NhPersonInfo.AccountYear), _NhPersonInfo.CoopMedCode, _NhPersonInfo.AiIDNo, int.Parse(_NhPersonInfo.DiagNo), sb ); if (iHr < 0) { throw new Exception(sb.ToString()); } conn.Open(); trans = conn.BeginTransaction(); hisDb.Transaction = trans; hisDb.ExecuteCommand("delete from wynhfeelist where zyh={0}", zyh); hisDb.ExecuteCommand("update jzd set sb_upload=0 where zyh={0}", zyh); trans.Commit(); } catch (System.Exception ex) { if (trans != null) { trans.Rollback(); } hr = ex.Message; } finally{ conn.Close(); } return(hr); }
public bool ExecuteNonQuery(string query) { if (Conectar()) { command = new SqlCommand(); command.Connection = sqlConn; command.CommandType = CommandType.Text; command.CommandText = query; transaction = sqlConn.BeginTransaction(); command.Transaction = transaction; try { SqlCommandBuilder.DeriveParameters(command); command.ExecuteNonQuery(); transaction.Commit(); Desconectar(); return true; } catch (SqlException sqlEx) { transaction.Rollback(); mensajeSQLExcepcion = sqlEx.Message; return false; } catch (Exception ex) { transaction.Rollback(); mensajeExcepcion = ex.Message; return false; } } return false; }
public void deletecompany() { //if (MessageBox.Show("คุณต้องการลบชื่อบริษัท ใช่หรือไม่?", "คำยืนยัน", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes) //{ tr = Conn.BeginTransaction(); try { sb = new StringBuilder(); sb.Append("DELETE Company"); sb.Append(" WHERE (CompanyId=@CompanyID)"); string sqlDelete; sqlDelete = sb.ToString(); com.CommandText = sqlDelete; com.CommandType = CommandType.Text; com.Connection = Conn; com.Transaction = tr; com.Parameters.Clear(); com.Parameters.Add("@CompanyID", SqlDbType.NVarChar).Value = txtCompanyId.Text.Trim(); int result; result = com.ExecuteNonQuery(); if (result == 0) { tr.Rollback(); MessageBox.Show("ข้อมูลที่ต้องการลบไม่ถูกต้อง !!!", "ผลการทำงาน", MessageBoxButtons.OK, MessageBoxIcon.Information); txtCompanyId.SelectAll(); } else { tr.Commit(); //MessageBox.Show("ลบชื่อลูกค้า เรียบร้อยแล้ว !!!", "ผลการทำงาน", MessageBoxButtons.OK, MessageBoxIcon.Information); ShowData(); FormatCompanyList(); btnAdd.Enabled = true; btnEdit.Enabled = false; btnDelete.Enabled = false; } } catch (Exception ex) { tr.Rollback(); MessageBox.Show("เกิดข้อผิดพลาด เนื่องจาก " + ex.Message, "ผลการทำงาน", MessageBoxButtons.OK, MessageBoxIcon.Information); } //} }
/// <summary> /// 增加一条数据 /// </summary> public int Adds(Model.WxMessageModel model) { StringBuilder strSql = new StringBuilder(); strSql.Append("insert into Wx_messageinfo("); strSql.Append("[MsgType],Contents,PicUrl,PShow,Title,Description,Url,HUrl,GroupCode,CreateTime,Author,OrderId)"); strSql.Append(" values ("); strSql.Append("@MsgType,@Contents,@PicUrl,@PShow,@Title,@Description,@Url,@HUrl,@GroupCode,@CreateTime,@Author,@OrderId)"); strSql.Append(";select @@IDENTITY"); SqlParameter[] parameters = { new SqlParameter("@MsgType", model.MsgType), new SqlParameter("@Contents", model.Contents), new SqlParameter("@PicUrl", model.PicUrl), new SqlParameter("@PShow", model.PShow), new SqlParameter("@Title", model.Title), new SqlParameter("@Description", model.Description), new SqlParameter("@Url", model.Url), new SqlParameter("@HUrl", model.HUrl), new SqlParameter("@GroupCode", model.GroupCode), new SqlParameter("@CreateTime", model.CreateTime), new SqlParameter("@Author", model.Author), new SqlParameter("@OrderId", model.OrderId) }; using (SqlConnection conn = new SqlConnection(SqlHelper.ConnectionString)) { if (conn.State != ConnectionState.Open) { conn.Open(); } using (System.Data.SqlClient.SqlTransaction trans = conn.BeginTransaction()) { try { SqlHelper.ExecuteNonQuery(trans, CommandType.Text, strSql.ToString(), parameters); //return i; string a = SqlHelper.ExecuteDataTable(trans, CommandType.Text, "select @@IDENTITY").Rows[0][0].ToString(); trans.Commit(); return(Convert.ToInt32(a)); } catch (Exception) { trans.Rollback(); return(0); } } } }
public static ResultadoTransaccion ActualizarNaviera(Int64 id, string nombre, string relacionPuertos) { resTransaccion = new ResultadoTransaccion(); try { //Abrir Conexion conn = BaseDatos.Conexion(); //Crear Transaccion transaction = conn.BeginTransaction(); //Actualizar //objParams = SqlHelperParameterCache.GetSpParameterSet(BaseDatos.Conexion(), "SP_A_CLIENTES_DIRECCION"); objParams = SqlHelperParameterCache.GetSpParameterSet(conn, "SP_U_PAPERLESS_NAVIERA"); objParams[0].Value = id; objParams[1].Value = nombre; SqlCommand command = new SqlCommand("SP_U_PAPERLESS_NAVIERA", conn, transaction); command.Parameters.AddRange(objParams); command.CommandType = CommandType.StoredProcedure; command.ExecuteNonQuery(); transaction.Commit(); resTransaccion.Estado = Enums.EstadoTransaccion.Aceptada; resTransaccion.Accion = Enums.AccionTransaccion.Actualizar; resTransaccion.ObjetoTransaccion = id; //Registrar Actividad //LogActividadUsuarios log = new LogActividadUsuarios(cuenta.GetType().ToString(), cuenta.Id, Enums.TipoActividadUsuario.Edito, Base.Usuario.UsuarioConectado.Usuario); //LogActividades.clsLogActividadUsuariosADO.GuardaActividad(log); CreaRelacionPuertos(id, relacionPuertos, conn); resTransaccion.Descripcion = "Se actualizó naviera '" + nombre + "'."; } catch (Exception ex) { transaction.Rollback(); Log.EscribirLog(ex.Message); resTransaccion.Estado = Enums.EstadoTransaccion.Rechazada; resTransaccion.Descripcion = ex.Message; } finally { conn.Close(); } return resTransaccion; }
public int CreateWorkProcess(WorkProcess newWorkProcess) { int result = -1; try { conn = db.openConn(); tr = conn.BeginTransaction(); sb = new StringBuilder(); sb.Remove(0, sb.Length); sb.Append("INSERT INTO tbWorkprocess(psnCode,psnFullName,wpDate,wpLast,wpOt,wplacking,wpmsalary,wpmOt,wpOrther)"); sb.Append(" VALUES (@psnCode,@psnFullName,@wpDate,@wpLast,@wpOt,@wplacking,@wpmsalary,@wpmOt,@wpOrther)"); string sqlsave; sqlsave = sb.ToString(); comm = new SqlCommand(); comm.Connection = conn; comm.Transaction = tr; comm.CommandText = sqlsave; comm.Parameters.Clear(); comm.Parameters.Add("@psnCode", SqlDbType.NVarChar).Value = newWorkProcess.psnCode; comm.Parameters.Add("@psnFullName", SqlDbType.NVarChar).Value = newWorkProcess.psnFullName; comm.Parameters.Add("@wpDate", SqlDbType.NVarChar).Value = newWorkProcess.wpDate; comm.Parameters.Add("@wpLast", SqlDbType.NVarChar).Value = newWorkProcess.wpLast; comm.Parameters.Add("@wpOt", SqlDbType.NVarChar).Value = newWorkProcess.wpOt; comm.Parameters.Add("@wplacking", SqlDbType.NVarChar).Value = newWorkProcess.wplacking; comm.Parameters.Add("@wpmsalary", SqlDbType.NVarChar).Value = newWorkProcess.wpmsalary; comm.Parameters.Add("@wpmOt", SqlDbType.NVarChar).Value = newWorkProcess.wpmOt; comm.Parameters.Add("@wpOrther", SqlDbType.NVarChar).Value = newWorkProcess.wpOrther; comm.ExecuteNonQuery(); tr.Commit(); result = 1; } catch (Exception ex) { tr.Rollback(); conn.Close(); return result; throw ex; } finally { conn.Close(); } return result; }
//query public void MS_ExecuteNonQuery(string sqlcmd) { try { MS_Connection(); st = scon.BeginTransaction(); new SqlCommand(sqlcmd, scon, st).ExecuteNonQuery(); st.Commit(); } catch (SqlException sqlError) { st.Rollback(); throw sqlError; } }
private void EliminaForUPD(System.Data.SqlClient.SqlTransaction transaccion) { try { //SqlParameter pFacturaTerceroID = new SqlParameter("@FacturaTerceroID", Utiles.BaseDatos.IntToSql(FacturaTerceroID)); //SqlParameter pUsuarioID = new SqlParameter("@UsuarioID", Utiles.BaseDatos.IntToSql(UsuarioID)); Config.Conexion.EjecutarSinResultados(transaccion, "FacturaTerceroDEL", Utiles.BaseDatos.IntToSql(FacturaTerceroID), Utiles.BaseDatos.IntToSql(UsuarioID)); } catch (Exception ex) { transaccion.Rollback(); Exception ex1 = new Exception("No se pudo actualizar la factura."); throw ex1; } }
public int CreateLoan(Loan newLoan) { int result = -1; try { conn = db.openConn(); tr = conn.BeginTransaction(); sb = new StringBuilder(); sb.Remove(0, sb.Length); sb.Append("INSERT INTO tbRoan(psnCode,LID,lmoney,term,lowmoney,loandate,reasonloan,complete)"); sb.Append(" VALUES (@psnCode,@LID,@lmoney,@term,@lowmoney,@loandate,@reasonloa,@complete)"); string sqlsave; sqlsave = sb.ToString(); comm = new SqlCommand(); comm.Connection = conn; comm.Transaction = tr; comm.CommandText = sqlsave; comm.Parameters.Clear(); comm.Parameters.Add("@psnCode", SqlDbType.NVarChar).Value = newLoan.person.psnCode; comm.Parameters.Add("@LID", SqlDbType.NVarChar).Value = newLoan.ID; comm.Parameters.Add("@lmoney", SqlDbType.NVarChar).Value = newLoan.lmoney; comm.Parameters.Add("@term", SqlDbType.NVarChar).Value = newLoan.term; comm.Parameters.Add("@lowmoney", SqlDbType.NVarChar).Value = newLoan.lowmoney; comm.Parameters.Add("@loandate", SqlDbType.NVarChar).Value = newLoan.loandate; comm.Parameters.Add("@reasonloa", SqlDbType.NVarChar).Value = newLoan.reasonLoan; comm.Parameters.Add("@complete", SqlDbType.NVarChar).Value ="0"; comm.ExecuteNonQuery(); tr.Commit(); result = 1; } catch (Exception ex) { tr.Rollback(); conn.Close(); return result; throw ex; } finally { conn.Close(); } return result; }
private void btnDelete_Click(object sender, EventArgs e) { var id = StudentByMatricNumber.GetMatricNumber(txtSearch.Text); var r = MessageBox.Show(@"Are you sure you want to DELETE? DELETING this record, deletes records in RELATED tables", @"Nacoss eVoting System", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2, MessageBoxOptions.DefaultDesktopOnly); if (r == DialogResult.Yes) { using (_cnn = new SqlConnection(NacossVotingSystem.Properties.Settings.Default.DBConn)) { _cnn.Open(); _myTransaction = _cnn.BeginTransaction(); using (_cmd = new SqlCommand("spDeleteCandidateById", _cnn)) { _cmd.CommandType = CommandType.StoredProcedure; _cmd.Transaction = _myTransaction; _cmd.Parameters.AddWithValue("@candidateID", id); var getCandidateById = new GetAllRecordById(); var deleteById = getCandidateById.GetCandidatesById(txtSearch.Text); try { if (deleteById) { _cmd.ExecuteNonQuery(); _myTransaction.Commit(); MessageBox.Show(@"Record Successfully deleted", @"Nacoss eVoting System"); ClearAll(); notifyIcon1.BalloonTipIcon = ToolTipIcon.Info; notifyIcon1.BalloonTipTitle = @"Delete Data"; notifyIcon1.BalloonTipText = @"Record deleted successfully"; notifyIcon1.ShowBalloonTip(3000); } else MessageBox.Show(@"Record not found in the Database", @"Nacoss eVoting System"); } catch (SqlException ex) { MessageBox.Show(@"The transaction rollbacked due to " +ex.Message); _myTransaction.Rollback(); } } } } }
private void GuardarDetallePlanilla(System.Data.SqlClient.SqlTransaction transaccion, DsPlanillaRedespacho ds) { try { SqlParameter pPlanillaRedespachoID = new SqlParameter("@PlanillaRedespachoID", PlanillaRedespachoID); foreach (DsPlanillaRedespacho.DetalleRow dr in ds.Detalle) { Config.Conexion.EjecutarSinResultados(transaccion, "PlanillaRedespachoDetalleINS", PlanillaRedespachoID, dr.RedespachoID); } } catch (Exception ex) { transaccion.Rollback(); throw ex; } }
private void GuardarDetalle(System.Data.SqlClient.SqlTransaction transaction) { try { DsObjetivoIncentivoDescrip ds = DsObejtivos; foreach (DsObjetivoIncentivoDescrip.DatosRow dr in ds.Datos) { Config.Conexion.EjecutarSinResultados(transaction, "CategoriaPersonalObjetivoINS", Utiles.BaseDatos.IntToSql(CategoriaID), Utiles.BaseDatos.IntToSql(dr.ObjetivoIncentivoID)); } } catch (Exception ex) { transaction.Rollback(); throw ex; } }
public void ExecuteSqlTranWithIndentity(Hashtable SQLStringList) { using (System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(this.connectionString)) { sqlConnection.Open(); using (System.Data.SqlClient.SqlTransaction sqlTransaction = sqlConnection.BeginTransaction()) { System.Data.SqlClient.SqlCommand sqlCommand = new System.Data.SqlClient.SqlCommand(); try { int num = 0; foreach (DictionaryEntry dictionaryEntry in SQLStringList) { string cmdText = dictionaryEntry.Key.ToString(); System.Data.SqlClient.SqlParameter[] array = (System.Data.SqlClient.SqlParameter[])dictionaryEntry.Value; System.Data.SqlClient.SqlParameter[] array2 = array; for (int i = 0; i < array2.Length; i++) { System.Data.SqlClient.SqlParameter sqlParameter = array2[i]; if (sqlParameter.Direction == System.Data.ParameterDirection.InputOutput) { sqlParameter.Value = num; } } DbHelperSQLP.PrepareCommand(sqlCommand, sqlConnection, sqlTransaction, cmdText, array); int num2 = sqlCommand.ExecuteNonQuery(); array2 = array; for (int i = 0; i < array2.Length; i++) { System.Data.SqlClient.SqlParameter sqlParameter = array2[i]; if (sqlParameter.Direction == System.Data.ParameterDirection.Output) { num = Convert.ToInt32(sqlParameter.Value); } } sqlCommand.Parameters.Clear(); } sqlTransaction.Commit(); } catch { sqlTransaction.Rollback(); throw; } } } }
public int CreateCompleteNumber(CompleteNumber newCompleteNumber) { int result = -1; try { conn = db.openConn(); tr = conn.BeginTransaction(); sb = new StringBuilder(); sb.Remove(0, sb.Length); sb.Append("INSERT INTO complete_numbers(complete_no,part_name,model_id,scan_step,date_create,user_create_name,status)"); sb.Append(" VALUES (@complete_no,@part_name,@model_id,@scan_step,@date_create,@user_create_name,@status)"); string sqlsave; sqlsave = sb.ToString(); comm = new SqlCommand(); comm.Connection = conn; comm.Transaction = tr; comm.CommandText = sqlsave; comm.Parameters.Clear(); comm.Parameters.Add("@complete_no", SqlDbType.NVarChar).Value = newCompleteNumber.CompleteNo; comm.Parameters.Add("@part_name", SqlDbType.NVarChar).Value = newCompleteNumber.PartName; comm.Parameters.Add("@model_id", SqlDbType.NVarChar).Value = newCompleteNumber.ModelNo; comm.Parameters.Add("@scan_step", SqlDbType.NVarChar).Value = newCompleteNumber.ScanStep; comm.Parameters.Add("@date_create", SqlDbType.NVarChar).Value = newCompleteNumber.DateCretate; comm.Parameters.Add("@user_create_name", SqlDbType.NVarChar).Value = newCompleteNumber.UserCreateName; comm.Parameters.Add("@status", SqlDbType.NVarChar).Value = newCompleteNumber.Status; comm.ExecuteNonQuery(); tr.Commit(); result = 1; } catch (Exception ex) { tr.Rollback(); conn.Close(); return result; throw ex; } finally { conn.Close(); } return result; }
public void AddToLibrary() { try { using (var connection = new C.SqlConnection( "Server=tcp:igs.database.windows.net,1433;Database=IGS_database;User ID=Glonfindel;Password=Karol1995!;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" )) { connection.Open(); C.SqlTransaction transaction = connection.BeginTransaction("AddToLib"); using (C.SqlCommand cmd = new C.SqlCommand("IF NOT EXISTS (SELECT * FROM UserLibrary WHERE idUser = @userID AND idGame = @gameID) INSERT INTO UserLibrary VALUES (@userID, @gameID)")) { try { cmd.Connection = connection; cmd.Transaction = transaction; cmd.Parameters.Add("@userID", SqlDbType.Int).Value = Login.user.ID; cmd.Parameters.Add("@gameID", SqlDbType.Int).Value = this.ID; cmd.ExecuteNonQuery(); transaction.Commit(); } catch (Exception ex) { MessageBox.Show(ex.GetType().ToString()); MessageBox.Show(ex.Message); try { transaction.Rollback(); } catch (Exception ex2) { // This catch block will handle any errors that may have occurred // on the server that would cause the rollback to fail, such as // a closed connection. MessageBox.Show(ex2.GetType().ToString()); MessageBox.Show(ex2.Message); } } }; } } catch (C.SqlException e) { MessageBox.Show(e.Message); } }
// //Stores the answers in the Answer table, returns true if successful, else false // public bool submitAnswers(Answers [] a) { da = new SqlDataAdapter(); cb = new SqlCommandBuilder(da); conn.Open(); tran = conn.BeginTransaction(); da.SelectCommand = new SqlCommand( "Select * from Answers", conn, tran); ds = new DataSet(); da.Fill(ds, "Answers"); dt = ds.Tables["Answers"]; for (int i = 0; i < a.Length; i++) { drow = dt.NewRow(); drow["Employee_ID"] = a[i].employee_Id; drow["Exam_ID"] = a[i].exam_ID; drow["Question_ID"] = a[i].question_ID; drow["Answer"] = a[i].answer; drow["Marks"] = a[i].marks; dt.Rows.Add(drow); } try { int updates = da.Update(ds, "Answers"); } catch (Exception ex) { if (tran != null) { tran.Rollback(); tran = null; conn.Close(); return false; } } finally { if (tran != null) { tran.Commit(); tran = null; } } conn.Close(); return true; }
private void btnAdd_Click(object sender, EventArgs e) { if (txtSaleTypeName.Text.Trim() == "") { MessageBox.Show("กรุณาป้อนชื่อประเภทการขายก่อน !!!", "ผลการตรวจสอบ", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); txtSaleTypeName.Focus(); return; } if (MessageBox.Show("คุณต้องการเพิ่มประเภทการขายใหม่ ใช่หรือไม่?", "คำยืนยัน", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes) { tr = Conn.BeginTransaction(); try { sb = new StringBuilder(); sb.Append("INSERT INTO SaleHeadSaleType (SaleHeadSaleTypeId,SaleHeadSaleTypeName)"); sb.Append(" VALUES (@SaleHeadSaleTypeId,@SaleHeadSaleTypeName)"); string sqlAdd; sqlAdd = sb.ToString(); com.CommandText = sqlAdd; com.CommandType = CommandType.Text; com.Connection = Conn; com.Transaction = tr; com.Parameters.Clear(); com.Parameters.Add("@SaleHeadSaleTypeId", SqlDbType.NVarChar).Value = txtSaleTypeId.Text.Trim(); com.Parameters.Add("@SaleHeadSaleTypeName", SqlDbType.NVarChar).Value = txtSaleTypeName.Text.Trim(); com.ExecuteNonQuery(); tr.Commit(); MessageBox.Show("เพิ่มประเภทการขายใหม่ เรียบร้อยแล้ว !!!", "ผลการทำงาน", MessageBoxButtons.OK, MessageBoxIcon.Information); ClearAllData(); ShowData(); FormatdgvSaleTypeList(); SaleTypeId(); } catch { MessageBox.Show("คุณป้อนรหัสประเภทสินค้าซ้ำ !!!", "ผลการทำงาน", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); tr.Rollback(); } } txtSaleTypeId.Focus(); }
public int CreateBoxNumber(BoxNumber newBoxNumber) { int result = -1; try { conn = db.openConn(); tr = conn.BeginTransaction(); sb = new StringBuilder(); sb.Remove(0, sb.Length); sb.Append("INSERT INTO box_numbers(complete_no,quantity,suplier,date_create,user_create_name,status)"); sb.Append(" VALUES (@complete_no,@quantity,@suplier,@date_create,@user_create_name,@status)"); string sqlsave; sqlsave = sb.ToString(); comm = new SqlCommand(); comm.Connection = conn; comm.Transaction = tr; comm.CommandText = sqlsave; comm.Parameters.Clear(); comm.Parameters.Add("@complete_no", SqlDbType.NVarChar).Value = newBoxNumber.CompleteNo; comm.Parameters.Add("@quantity", SqlDbType.NVarChar).Value = newBoxNumber.Quantity; comm.Parameters.Add("@suplier", SqlDbType.NVarChar).Value = newBoxNumber.Suplier; comm.Parameters.Add("@date_create", SqlDbType.NVarChar).Value = newBoxNumber.DateCreate; comm.Parameters.Add("@user_create_name", SqlDbType.NVarChar).Value = newBoxNumber.UserCreateName; comm.Parameters.Add("@status", SqlDbType.NVarChar).Value = newBoxNumber.Status; comm.ExecuteNonQuery(); tr.Commit(); result = 1; } catch (Exception ex) { tr.Rollback(); conn.Close(); return result; throw ex; } finally { conn.Close(); } return result; }
public static ResultadoTransaccion GuardarDefinicionCredito(clsCreditoCliente ObjCredito) { ResultadoTransaccion res = new ResultadoTransaccion(); try { //Abrir Conexion conn = BaseDatos.Conexion(); //Crear Transaccion transaction = conn.BeginTransaction(); //Registrar Llamada Telefonica objParams = SqlHelperParameterCache.GetSpParameterSet(conn, "SP_N_DIRECCION_CREDITO_CLIENTE"); objParams[0].Value = ObjCredito.Id; objParams[1].Value = ObjCredito.ObjCuenta.Id; objParams[2].Value = ObjCredito.ObjMoneda.Id; objParams[3].Value = ObjCredito.MontoLineaCredito; SqlCommand command = new SqlCommand("SP_N_DIRECCION_CREDITO_CLIENTE", conn); command.Transaction = transaction; command.Parameters.AddRange(objParams); command.CommandType = CommandType.StoredProcedure; ObjCredito.Id = Convert.ToInt32(command.ExecuteScalar()); //Ejecutar transaccion transaction.Commit(); res.Estado = Enums.EstadoTransaccion.Aceptada; res.Descripcion = "Se registró el crédito del cliente correctamente"; } catch (Exception ex) { transaction.Rollback(); Log.EscribirLog(ex.Message); res.Descripcion = ex.Message; res.ArchivoError = "clsControlCreditoAdo.cs"; res.MetodoError = "GuardarDefinicionCredito"; res.Estado = Enums.EstadoTransaccion.Rechazada; } finally { conn.Close(); } return res; }
public HashSet<SprocResultInfo> GetResults(StoredProcedure sproc) { using (transaction = connection.BeginTransaction()) { var reader = ExecuteSqlReader(BuildFMTQuery(sproc)); var results = new HashSet<SprocResultInfo>(); if (!reader.IsClosed) { do { var schemaTable = reader.GetSchemaTable(); if (schemaTable != null) results.Add(SprocResultInfo.ScanSchema(schemaTable)); } while (reader.NextResult()); reader.Close(); } transaction.Rollback(); return results; } }
public SubmitOrderResult SaveOrder(SubmitOrderRequest request) { var result = new SubmitOrderResult(); orderNumber = request.OrderNumber; try { trans = cn.BeginTransaction(); var orderId = InsertOrderRecord(request); foreach (var orderLineItem in request.LineItems) { InsertLineItems(orderId, orderLineItem); } trans.Commit(); trans.Dispose(); trans = null; result = GetOrderResults(); } catch (SqlException ex) { result.HasException = true; result.Exception = ExceptionFactory.BuildSqlException(ex); } catch (Exception ex) { result.HasException = true; result.Exception = ExceptionFactory.BuildSystemException(ex); } finally { if (trans != null) { trans.Rollback(); trans.Dispose(); } cn.Close(); cn.Dispose(); } return result; }
public static ResultadoTransaccion EliminarLlamada(long IdLlamada) { long IdSalida; resTransaccion = new ResultadoTransaccion(); try { //Abrir Conexion conn = BaseDatos.Conexion(); //Crear Transaccion transaction = conn.BeginTransaction(); //Registrar Llamada Telefonica objParams = SqlHelperParameterCache.GetSpParameterSet(conn, "SP_E_VENTAS_LLAMADA_TELEFONICA"); objParams[0].Value = IdLlamada; SqlCommand command = new SqlCommand("SP_E_VENTAS_LLAMADA_TELEFONICA", conn); command.Transaction = transaction; command.Parameters.AddRange(objParams); command.CommandType = CommandType.StoredProcedure; IdSalida = Convert.ToInt32(command.ExecuteScalar()); //Ejecutar transaccion transaction.Commit(); resTransaccion.Estado = Enums.EstadoTransaccion.Aceptada; resTransaccion.Descripcion = "Se eliminó Llamada Telefónica Exitosamente"; } catch (Exception ex) { transaction.Rollback(); Log.EscribirLog(ex.Message); resTransaccion.Descripcion = ex.Message; resTransaccion.ArchivoError = "clsLlamadaTelefonicaAdo.cs"; resTransaccion.MetodoError = "EliminarLlamada"; resTransaccion.Estado = Enums.EstadoTransaccion.Rechazada; } finally { conn.Close(); } return resTransaccion; }
public int CreateMoneySum(MoneySum newMoneySum) { int result = -1; try { conn = db.openConn(); tr = conn.BeginTransaction(); sb = new StringBuilder(); sb.Remove(0, sb.Length); sb.Append("INSERT INTO tbMomeySum(psnCode,sumDate,amountwase,amountsum)"); sb.Append(" VALUES (@psnCode,@sumDate,@amountwase,@amountsum)"); string sqlsave; sqlsave = sb.ToString(); comm = new SqlCommand(); comm.Connection = conn; comm.Transaction = tr; comm.CommandText = sqlsave; comm.Parameters.Clear(); comm.Parameters.Add("@psnCode", SqlDbType.NVarChar).Value = newMoneySum.psnCode; comm.Parameters.Add("@sumDate", SqlDbType.NVarChar).Value = newMoneySum.sumDate; comm.Parameters.Add("@amountwase", SqlDbType.NVarChar).Value = newMoneySum.amountwase; comm.Parameters.Add("@amountsum", SqlDbType.NVarChar).Value = newMoneySum.amountsum; comm.ExecuteNonQuery(); tr.Commit(); result = 1; } catch (Exception ex) { tr.Rollback(); conn.Close(); return result; throw ex; } finally { conn.Close(); } return result; }
public int CreateReamMoney(ReamMoney newReamMoney) { int result = -1; try { conn = db.openConn(); tr = conn.BeginTransaction(); sb = new StringBuilder(); sb.Remove(0, sb.Length); sb.Append("INSERT INTO tbReamMoney(RID,psnCode,amount,reamdate)"); sb.Append(" VALUES (@RID,@psnCode,@amount,@reamdate)"); string sqlsave; sqlsave = sb.ToString(); comm = new SqlCommand(); comm.Connection = conn; comm.Transaction = tr; comm.CommandText = sqlsave; comm.Parameters.Clear(); comm.Parameters.Add("@RID", SqlDbType.NVarChar).Value = newReamMoney.ID; comm.Parameters.Add("@psnCode", SqlDbType.NVarChar).Value = newReamMoney.person.psnCode; comm.Parameters.Add("@amount", SqlDbType.NVarChar).Value = newReamMoney.amount; comm.Parameters.Add("@reamdate", SqlDbType.NVarChar).Value = newReamMoney.reamdate; comm.ExecuteNonQuery(); tr.Commit(); result = 1; } catch (Exception ex) { tr.Rollback(); conn.Close(); return result; throw ex; } finally { conn.Close(); } return result; }
public void Rollback() { if (sqlConnection != null) { if (sqlTransaction != null) { try { sqlTransaction.Rollback(); } catch (Exception) { } sqlTransaction = null; } sqlConnection.Close(); sqlConnection.Dispose(); sqlConnection = null; } }
public static bool ExecuteNonQuery(System.Data.SqlClient.SqlCommand[] sqlCmdArray) { if (Connection1.State == ConnectionState.Closed) { Connection1.Open(); } Transaction = Connection.BeginTransaction(); for (int i = 0; i < sqlCmdArray.Length; i++) { if (!ExecuteNonQuery(sqlCmdArray[i])) { Transaction.Rollback(); Connection1.Close(); return(false); } } Transaction.Commit(); Connection1.Close(); return(true); }
/// <summary> /// 事务处理 /// </summary> /// <param name="SqlList"></param> /// <returns></returns> public bool DoBatchWork(SortedList SqlList) { System.Data.SqlClient.SqlConnection conn; System.Data.SqlClient.SqlCommand dbCommand; System.Data.SqlClient.SqlTransaction tempTransaction = null; int i; string tempSql; conn = new SqlConnection(mConnectInfo); dbCommand = new SqlCommand(); dbCommand.Connection = conn; try { conn.Open(); //建立数据库连接 tempTransaction = conn.BeginTransaction(); for (i = 0; i <= SqlList.Count - 1; i++) { tempSql = SqlList.GetByIndex(i).ToString(); dbCommand.Transaction = tempTransaction; dbCommand.CommandText = tempSql; dbCommand.ExecuteNonQuery(); } //提交事务 tempTransaction.Commit(); return(true); } catch (System.Data.SqlClient.SqlException e) { tempTransaction.Rollback(); throw new Exception(e.Message); } finally { conn.Close(); } }
protected void btnReviseForApp_Click(object sender, System.EventArgs e) { Label label = (Label)base.Master.FindControl("lbltotalinfo"); this.cn.Open(); System.Data.SqlClient.SqlTransaction transaction = this.cn.BeginTransaction(); try { if (this.grdForApproval.Rows.Count > 0) { for (int i = 0; i < this.grdForApproval.Rows.Count; i = (int)(i + 1)) { CheckBox box = (CheckBox)this.grdForApproval.Rows[i].FindControl("chkSelectforApp"); if (box.Checked) { string str = this.grdForApproval.Rows[i].Cells[3].Text.Trim(); string[] strArray = new string[] { "@PONO", "@revuser" }; string[] strArray2 = new string[] { str.Trim(), this.Session["Uid"].ToString() }; this._mc.MC_Save_nodt_tr("Sp_Smt_BOM_PORevise", this.cn, transaction, strArray, strArray2); } } } transaction.Commit(); label.Text = ("Revised Successfully"); //this.bindforapproval(); //this.bindapprove(); //this.bindrevised(); } catch (System.Exception) { transaction.Rollback(); label.Text = ("Unable to Revise"); } finally { this.cn.Close(); } }