2014-12-05 127 views
0

我最近得到了一個ASP類網站。並有一個奇怪的問題。asp插入數據庫重複數據

語言:ASP。

數據庫:Oracle,

當我插入數據庫。如果有重複的數據(這裏忽略了Oracle主鍵setting.it是一個老的系統,我們最好不要更改數據庫。) 那麼我們的驗證之前插入DB:

sql="select 1 from tablename where condition...." 
result=runsql(sql) 
if not result.eof then 
'here means DB has data already then we return false. and exit the function. 
exit function 
end if 

'Insert Into DB statement 

我用批處理文件上傳。意味着文件有很多記錄。例如50個記錄。 然後我們用兩臺電腦打開本網站並點擊提交按鈕同時上傳文件。

我們發現數據庫有一些重複的data.only部分,不是全部。

我不知道發生了什麼事。我們在插入數據庫之前已經添加了驗證。

有人可以幫助我嗎?

這個網站沒有線程的東西。

+0

查找「比賽條件」。祝你好運。 – 2014-12-05 03:39:19

+0

那麼有什麼解決辦法? – 2014-12-05 08:17:10

回答

0

問題是您的代碼中存在爭用條件。從邏輯上看來,你的代碼如下所示:

Open file 

Repeat 
    Read record from file 
    Check if record exists in table 
    If no record in table 
    Add record to table 
End repeat 

Close file 

的競爭條件是,如果你必須在執行兩道工序,每一個可以檢查,看看是否在表中存在一個特定的記錄;兩者都會返回一個表示記錄不存在的返回值;然後雙方將繼續插入記錄。顯然,數據庫中沒有主鍵或唯一鍵約束來防止重複數據,因此每個進程插入的數據都被添加到表中。

您遇到的情況發生是因爲兩個進程不知道對方正在做什麼。每個進程都是獨立調度的,並且不僅在它們之間共享處理器,而且與所有其他進程同時運行,並且它們的執行被不可預知地中斷以允許其他進程運行。現在,讓我們考慮以下情況:

Process 1 starts 
Process 2 starts 
Process 1 issues an I/O request to read a record from the 
    file, relinquishing the CPU 
Process 2 issues an I/O request to read a record from the 
    file, relinquishing the CPU 
I/O for process 1 completes and process 1 is rescheduled for execution 
I/O for process 2 completes and process 2 is rescheduled for execution 
Process 2 executes, issues an SQL request to see if the record exists in the 
    table, and relinquishes the CPU 
Process 1 executes, issues the same SQL request, and relinquish the CPU 
SQL request for process 2 completes; process 2 is rescheduled for execution 
SQL request for process 1 completes; process 1 is rescheduled for execution 
Process 1 executes and finds the record does not exist in the file 
    Process 1 adds the record to the file 
Process 2 executes and finds the record does not exist in the file 
    Process 2 adds the record to the file 

請注意,進程的執行順序已經交換了幾次。這是正常的 - 你無法控制哪個進程將被安排執行,你也不需要關心它。

您的每個進程都已正確找到來自該文件的記錄在查看數據庫時不存在並因此添加它。不幸的是,你的每一個進程都不知道另一個進程或多或少地在同一時間執行完全相同的事情。

IMO最容易做的事情是讓每個進程都試圖鎖定文件,以便只讀取文件。這會阻止其他進程讀取和處理文件中的數據,從而防止出現這種問題。它看起來像你使用VB.Net,所以你應該能夠使用FileSystem.Lock來鎖定文件。您的程序的邏輯流程將改爲如下所示:

Open file 

Lock the file 
    - either wait until the file can be locked successfully or terminate because the 
    file is in use by another process 

Repeat 
    Read record from file 
    Check if record exists in table 
    If no record in table 
    Add record to table 
End repeat 

Unlock the file 

Close file 

祝您好運。

+0

感謝您的耐心和細節回覆。對不起,有關鎖的一個問題,不同的PC上傳不同的文件。只有該文件具有重複的數據。如果鎖定文件,意味着這個文件不能共享讀取。但我們上傳不同的文件。這樣可以嗎? – 2014-12-08 06:29:09