简体   繁体   中英

Sql transaction c# - exits try when ExecuteNonQuery() is run

I'm trying to implement an sql transaction, however, i've run into a bit of bother. I have a simple database with has three tables. Users, Post and Comments. I wish to implement a delete button that will delete a user from the Users table. The initial problem I had was that I needed to remove the users FK from both the post and comment table, then remove the user from the User table. I looked online and somebody had suggested using transaction for multiple server calls. Here is my code:

public void DeleteUser(int UserId)
    {
        using (SqlConnection con = new SqlConnection(connectionString))
        {
            con.Open();

            SqlTransaction sqlTran = con.BeginTransaction();

            try
            {
                using (SqlCommand command = new SqlCommand("DELETE FROM Comment WHERE UserId = " + @UserId, con))
                {
                    SqlParameter userid = new SqlParameter("@UserId", SqlDbType.Int);
                    userid.Value = UserId;
                    command.ExecuteNonQuery();
                }

                using (SqlCommand command = new SqlCommand("DELETE FROM Post WHERE UserId = " + @UserId, con))
                {
                    SqlParameter userid = new SqlParameter("@UserId", SqlDbType.Int);
                    userid.Value = UserId;
                    command.ExecuteNonQuery();
                }

                using (SqlCommand command = new SqlCommand("DELETE FROM Users WHERE UserId = " + @UserId, con))
                {
                    SqlParameter userid = new SqlParameter("@UserId", SqlDbType.Int);
                    userid.Value = UserId;
                    command.ExecuteNonQuery();
                }

                sqlTran.Commit();
            }
            catch
            {
                sqlTran.Rollback();
            }
        }
    }

The problem I have is that when the DeleteUser method is run, the program gets as far as the command.ExecutyNonQuery in the first using block, then jumps to the catch. Thus rolling back the changes. There isn't any error codes displayed, so i'm not sure what is going wrong.

Any help in this matter would be greatly appreciated.

You're missing command.Transaction = sqlTran; .

DO NOT USE try {} catch {} . Use at least try {} catch (Exception ex) {} -> this will give you enough information to solve the problem on your own.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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