C#更新SQLServer中的TimeStamp字段(时间戳) 防止同时修改一行时覆盖更新

分类: C#2012-10-24 15:10 1878人阅读 评论(0) 收藏 举报

public partial class Form1 : Form
    {
        private SqlConnection mCnn = null;
        private long TimeStampValue;

public Form1()
        {
            InitializeComponent();
            mCnn = new SqlConnection();
            mCnn.ConnectionString = "Data Source=192.168.18.205;Database=" +
                            "Test;Uid=sa;Pwd=kicpassword";
            mCnn.Open();
        }

        //读取

private void btnReadTimeStamp_Click(object sender, EventArgs e)
        {
            //使用convert(bigint,FTimeStamp) MyTimeStamp把FTimeStamp转换为bigint整数类型
            string strSQL = "Select Top 1 FCaption,convert(bigint,FTimeStamp) MyTimeStamp,FTimeStamp From t_TimeStamp";
            SqlCommand Cmd = new SqlCommand(strSQL, mCnn);
            SqlDataReader Reader = Cmd.ExecuteReader();
            while (Reader.Read())
            {
                long value = (long)Reader["MyTimeStamp"];
                TimeStampValue = value;    //在此处把TimeStamp的值赋值给变量,用于更新时判断
                txtTimeStamp.Text = value.ToString();
                txtTimeStampHex.Text=value.ToString("X16");
            }
            Reader.Close();
            Reader = null;
        }

//更新

private void btnUpdateTimeStamp_Click(object sender, EventArgs e)
        {
            //Where条件加上TimeStamp的判断,必须和读取的一致,用于并发操作
            string strSQL = "Update t_TimeStamp Set FCaption = '修改记录'" +
                                " Where FTimeStamp =" + TimeStampValue.ToString();
            SqlCommand cmd = new SqlCommand(strSQL, mCnn);
            int UpdateCount = cmd.ExecuteNonQuery();
            if (UpdateCount <= 0)
            {
                MessageBox.Show("更新失败!");
            }
            else
            {
                MessageBox.Show("更新成功!");                                    
            }
        }
    }

转自:http://blog.csdn.net/limlimlim/article/details/8107228

上一篇:Apache Curator: Zookeeper客户端


下一篇:A除以B问题