且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何防止重复记录在我的数据库,同时更新记录?

更新时间:2023-01-29 20:30:38

如果您的应用程序支持,你需要确保变更不会被你的重复检查和更新数据库之间的另一个用户进行多用户。

If your application supports multiple users you need to ensure changes are not made by another user between your check for duplicates and the database update.

要最简单的方法做到这一点是因为mbeckish建议,创建标题列的唯一约束:

The easiest way to do this is as mbeckish suggested, create a UNIQUE constraint on the title column:

ALTER TABLE maindatabase.animelist 
ADD CONSTRAINT U_animelist_TitleAnime UNIQUE (TitleAnime)

数据库引擎,然后将实施独特的游戏,和你的客户机可以处理用户反馈通过捕获任何约束违反异常:

The database engine will then enforce unique titles and your client can handle user feedback by catching any constraint violation exception:

void checkData()
{
    SuspendLayout();
    try
    {

        updateData();

    }
    catch (Exception ex)
    {
        MySqlException sqlEx = ex as MySqlExecption;
        // If there is a constraint violation error.
        // (I may have the wrong error number, please test.)
        if (sqlEx != null && sqlEx.Number == 1062) 
        {
            my = Form.ActiveForm as MyList;
            my.msg = new Message_Box();
            my.msg.Descrip.Text = "Record is already in the Database";
            my.msg.Title.Text = "Duplicate Record";
            my.msg.ShowDialog();
        } 
        else 
        {
            MessageBox.Show("" + ex);
        }
    }
    finally
    {
        ResumeLayout();
    }
}