如何在sqltransaction中读取未提交的事务?

时间:2012-08-15 16:30:55

标签: asp.net .net sql .net-2.0

我在.net framework 2.0 c#code

中使用SQLTransaction时遇到了问题

这是我的代码:

public bool register()
    {
        SqlConnection conn = DB.getInstance().getConnection();
        conn.Open();
        SqlTransaction sqlTransaction = conn.BeginTransaction();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;
        cmd.Transaction = sqlTransaction;          

        try
        {
            cmd = insertMembers(cmd);
            cmd.ExecuteNonQuery();

            SqlDataReader read = null;
            cmd.CommandText = "SELECT * FROM members WHERE username='" + username + "'";
            read = cmd.ExecuteReader();
            while (read.HasRows)
            {
                id0 = (int)read["id0"];
            }

            cmd = insertMembersBalance(cmd);
            cmd.ExecuteNonQuery();

            cmd = insertMembersEPoint(cmd);
            cmd.ExecuteNonQuery();

            cmd = insertMembersVerify(cmd);
            cmd.ExecuteNonQuery();

            reset();

            sqlTransaction.Commit();
        }
        catch(Exception e)
        {                
            sqlTransaction.Rollback();
            Console.WriteLine(e.ToString());
            return false;
        }
        finally
        {
            conn.Close();
        }

        return true;
    }

我无法从成员表中获取用于将另一个记录插入另一个表的内容。

还有其他解决方案吗?

2 个答案:

答案 0 :(得分:0)

您必须先调用dr.Read()而不是SqlDataReader dr = cmd.........

答案 1 :(得分:0)

        if (read.HasRows)  // needs to be if not while or it will just loop
        {
             read.Read();
             id0 = (int)read["id0"];
        }
        read.Close();      // need to close the reader before you can use the cmd

        if you want to loop through all rows then 

        while (read.Read())
        {
             id0 = (int)read["id0"];
        }