简体   繁体   English

使用ADO.NET不能进行回滚事务

[英]Rollback transaction does not work witH ADO.NET

I am working on a C# application with Mysql database(version 5.5). 我正在使用Mysql数据库(5.5版)开发C#应用程序。 I am facing an issue where I need to catch an exception occurred in Mysql. 我面临一个需要捕获Mysql中发生的异常的问题。 It doesn't matter whether it is caught in Mysql or in dotNet. 捕获在Mysql还是dotNet中都没有关系。 The problem is that I want to rollback all my previous work when an exception/error is occurred; 问题是,当发生异常/错误时,我想回滚所有以前的工作; be it of MySqlException or custom one. 是MySqlException还是自定义之一。 And yes, I tried using TransactionScope and MySqlTransaction but it didn't rollback my work. 是的,我尝试使用TransactionScope和MySqlTransaction,但没有回滚我的工作。

public int AddDeviceNew(string IMEI, string Sim, TextBox veh_reg, RadioButtonList veh_icon, RadioButtonList vehicle_type, DropDownList group, DropDownList ddlIsDimts, HiddenField hid_requested_id)
{
    if (conn.State == ConnectionState.Closed)
    {
        conn.Open();
    }
       Common_Functions com_Obj = new Common_Functions();
        int deviceid;
        Int64 serviceid;
        string logText;
        long Sim_Id;
        MySqlCommand command = conn.CreateCommand();
        MySqlTransaction trans = conn.BeginTransaction();

                //command.Connection = conn;
                //command.CommandText = "SET autocommit = 0";
                //command.ExecuteNonQuery();

                command.CommandText = "select ffc_status from devices where imei='" + IMEI + "'";
                string strdeviceFFCstatus = Convert.ToString(command.ExecuteScalar());

                command.CommandText = "select ffc_status from mobile_simcards where mobile_no=" + Sim;
                string strSIMFFCstatus = Convert.ToString(command.ExecuteScalar());

                if (strSIMFFCstatus == "1")
                {
                    command.CommandText = "delete from mobile_simcards where mobile_no=" + Sim;
                    command.ExecuteNonQuery();
                }

                command.CommandText = "insert into mobile_simcards(network,mobile_no,created,last_updated) values(2,'" + Sim + "',now(),now())";
                command.ExecuteNonQuery();
                long SimID = command.LastInsertedId;

                if (strdeviceFFCstatus == "1")
                {
                    command.CommandText = "delete from devices where imei='" + IMEI + "'";
                    command.ExecuteNonQuery();
                }
                logText = "--------------------------------------\nDate: " + DateTime.Now.ToString("G") + "\nNotes: \n**Created**\n--------------------------------------\n";



                command.CommandText = "insert into devices (sys_user_id,sys_type,sys_simcard,imei,serial_no,fleet_key,heartbeat_type,odometer_offset,hours_offset,`log`,notes) values('3114','15','" + SimID + "','" + IMEI + "','" + IMEI + "','Shggg123',0,'54718','43200','" + logText + "','')";
                command.ExecuteNonQuery();
                //Sim_Id = command.LastInsertedId;

                deviceid = Convert.ToInt16(command.LastInsertedId);

                //----------For MiCar-------------
                //if (group.SelectedItem.Text == "4551")
                //{
                //    for (int i = 1; i <= 30; i++)
                //    {
                //        command.CommandText = "insert into devicemappingrfid values(" + i + "," + deviceid + ",'',0,1,now())";
                //        command.ExecuteNonQuery();

                //    }
                //}
                //--------------------------------
                logText = "--------------------------------------\nDate: " + DateTime.Now.ToString("G") + "\nNotes: \n**Created**\n--------------------------------------\n";
                command.CommandText = "insert into services(sys_user_id,sys_sage_reference,sys_created,sys_renewal_due,sys_renewal_cost,sys_device_id,veh_reg,veh_icon_1,veh_icon_2,veh_body,veh_chasis,veh_year,veh_seats,veh_avempg,veh_costpermile,veh_wd_auth_start,veh_wd_auth_end,veh_we_auth_start,veh_we_auth_end,veh_sun_auth_start,veh_sun_auth_end,veh_type,`log`,veh_type_name,is_dimts) values(3114,345,now(),'0001-01-01 00:00:00','0.0','" + deviceid + "','" + Regex.Replace(veh_reg.Text, "[^0-9a-zA-Z]+", "") + "','" + veh_icon.SelectedValue + "','','','','','0','0.0','0.0','00:00','00:00','00:00','00:00','00:00','23:59','" + vehicle_type.SelectedValue.ToString() + "','" + logText + "','" + vehicle_type.SelectedItem.Text + "'," + Convert.ToInt16(ddlIsDimts.SelectedValue) + ")";
                command.ExecuteNonQuery();
                serviceid = Convert.ToInt64(command.LastInsertedId);

                command.CommandText = "insert into group_services (sys_service_id,sys_group_id,sys_added_date) values(" + serviceid + ",'1998',now())";
                command.ExecuteNonQuery();
                logText = "--------------------------------------\nDate: " + DateTime.Now.ToString("G") + "\nNotes: \nAdded to Vimal\n--------------------------------------\n";
                command.CommandText = "update services set log=CONCAT(log,'" + logText + "') where id='" + serviceid + "'";
                command.ExecuteNonQuery();

                command.CommandText = "insert into tbl_history_devices (`sys_group_id`,`sys_service_id`) values('1998','" + serviceid + "')";
                command.ExecuteNonQuery();

                command.CommandText = "select name from `group` where id='" + group.SelectedValue + "'";
                string groupName = (string)command.ExecuteScalar();

                if (group.SelectedValue != "1998")
                {
                    command.CommandText = "insert into group_services (sys_service_id,sys_group_id,sys_added_date) values(" + serviceid + "," + group.SelectedValue + ",now())";
                    command.ExecuteNonQuery();
                    logText = "--------------------------------------\nDate: " + DateTime.Now.ToString("G") + "\nNotes: \nAdded to " + groupName + "\n--------------------------------------\n";
                    command.CommandText = "update services set log=CONCAT(log,'" + logText + "') where id='" + serviceid + "'";
                    command.ExecuteNonQuery();

                    command.CommandText = "insert into tbl_history_devices (`sys_group_id`,`sys_service_id`) values('" + group.SelectedValue + "','" + serviceid + "')";
                    command.ExecuteNonQuery();

                    //--------------------------------------------------------------------------------------------------------------------------------------------
                    command.CommandText = "insert into device_mapping (device_id,device_imei,sys_simcard,vehID,NewVehID,repair_with_IMEI,reason,device_placed,current_mapped_status) values('" + deviceid + "','" + IMEI + "','" + SimID + "','" + serviceid + "','','','','',1)";
                    command.ExecuteNonQuery();
                    //--------------------------------------------------------------------------------------------------------------------------------------------


                }
                command.CommandText = "insert into latest_telemetry (sys_service_id,sys_msg_type,sys_proc_time,sys_proc_host,sys_geofence_id,sys_device_id,gps_time,jny_distance,jny_duration,jny_idle_time,jny_leg_code,jny_device_jny_id,des_movement_id,des_vehicle_id,tel_hours,tel_input_0,tel_input_1,tel_input_2,tel_input_3,tel_temperature,tel_voltage,tel_odometer) values('" + serviceid + "','0',date_add(now(),interval -330 minute),'None','0','" + deviceid + "',now(),'0.0','0','0','0','0','0','0','0',false,false,false,false,'0.0','0.0','0')";
                command.ExecuteNonQuery();


                if (hid_requested_id.Value != "")
                {
                    command.CommandText = "update requested_device set device_status=1 where id=" + Convert.ToInt16(com_Obj.Safe(hid_requested_id.Value)) + "";
                    command.ExecuteNonQuery();
                }
                trans.Commit();
                trans.Rollback();
                command.Dispose();
                return 1;
            }

In your code you are trying to commit the transaction and then rollback it in the next line: 在您的代码中,您尝试提交事务,然后在下一行回滚它:

trans.Commit();
trans.Rollback();

What's the point in that? 这有什么意义? At this point rollback will surely not work, as the transaction is already committed. 此时,由于事务已经提交,因此回滚肯定将不起作用。

I suggest updating the code to follow structure similar to this: 我建议更新代码以遵循类似于以下的结构:

MySqlCommand command = conn.CreateCommand();
MySqlTransaction trans = conn.BeginTransaction();
try
{
    // Perform everything that you need, all queries, updates, etc.
    trans.Commit();    // this line would be executed only if no exceptions were thrown
}
catch
{
    // Your error handling code
    trans.Rollback();    // rollback is only executed when exception is thrown
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM