在C#中插入时如何锁定表 [英] how to lock table when inserting in c#

查看:208
本文介绍了在C#中插入时如何锁定表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有多个用户,并且记录超过50K.

我整天有多个用户在同一张表中插入记录,大多数时候数据混杂在一起.我有一个标题/详细信息输入表单网页.

我的插入发生在用户单击提交"按钮时,它将选择数据库中的下一个可用编号并将其用作我的主键来插入记录(标题/详细信息).
大多数情况下,两个用户同时获得主键.

如果您可以将我重定向到具有锁定解决方案的站点,或者可以帮助我解决问题
我的解决方案,但有时失败:

Hi,

I have multiple users and more than 50K of records.

I have multiple users inserting records at the same in one table throughout the day and most of the time data got mixed up. I have a header/detail entry form web page.

My insert occurs when the users click the Submit button, it will SELECT the next available number from DB and use it as my Primary key to insert record (header/detail).
Most of the time 2 users get the primary key at the same time.

If you could redirect me to the site with has the solution in locking or help me in my problem
My Solution but sometimes it failed:

bool blnExist = false;
while (!blnExist)
{
  string sKdey = PopulateDraftNumber();
  if (IfKeyExists(sKdey))
  {
    blnExist = false; //found record, reselect another key
  }
  else
   {
    blnExist = true; //found no record insert into table
    lblRequestNo.Text = sKdey;
    INSERT RECORD INTO TABLE
   }
}


1-询问服务器密钥

这是用户获得各自记录的两个1键的时间.,

2-将该密钥附加到我的记录
-在步骤3之前,我想在这部分上加锁---
3-将记录发送到服务器-错误的主键约束.


1- Ask the server for a key

This is when users get two 1 key for their respective records.,

2- Attach that key to my Record
-- I WANT SOME SORT OF LOCKING HERE ON THIS PART BEFORE STEP 3 ---
3- Send record to server - ERROR PRIMARY KEY CONSTRAINTS.

推荐答案

大多数情况下,两个用户同时获得主键.

这是因为您的代码正在生成它自己的主键.这应该留给数据库.在数据库中插入新记录(不包含键值)和一个或多个必填字段,然后由数据库分配键值.以适当的IDENTITY进行检索,并使用分配的键完成该记录的INSERTS或UPDATES.在此处阅读更多信息 [
Most of the time 2 users get the primary key at the same time.

This is because you''re code is generating it''s own primary keys. This should be left up to the database. Insert a new record in the database (without the key value) and one or more required fields and let the database assign the key value. Retrieve that with an appropriate IDENTITY and finish your INSERTS or UPDATES of that record using the assigned key. Read more on it here[^].

Locking tables is frowned upon because it turns you''re multi user app into a signle user app until the lock is gone. If your app crashes before the lock is freed, your database table is locked until an admin goes and clears it manually.


这篇关于在C#中插入时如何锁定表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆