从这样的表格中:
ID SEQUENCE
1 1
我想在每次访问表时递增序列值。到目前为止,我想出了这个vbscript:
Dim Result
On Error Resume Next
Result = GetSequential()
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objFile = objFS.CreateTextFile("result_" & Result & ".txt", False)
if err.Number <> 0 then
MsgBox err.Description & " (" & Err.Number & "): " & Result
end if
on error goto 0
wscript.echo "Next value: " & Result
Function GetSequential()
Dim cn, rs
Dim Sequential
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.connectionstring = "Driver={MySQL ODBC 5.2a Driver};Server=172.16.0.130;Database=testautostore;User=root;Password=aquilae"
cn.Open
Dim SqlCount
SqlCount = "select count(*) from counter where ID='1'"
rs.Open SqlCount, cn, adOpenStatic
If rs(0) = "1" Then
wscript.echo "Updating record..."
Dim SqlUpdate
SqlUpdate = "update counter set SEQUENCE=SEQUENCE + 1 where ID='1'"
cn.Execute SqlUpdate
Dim SqlSelect
SqlSelect = "select SEQUENCE from counter where ID='1'"
rs.Close
rs.Open SqlSelect, cn, adOpenStatic
Sequential = rs(0)
wscript.echo "Result: " & Sequential
End if
rs.Close
Set rs = Nothing
cn.Close
GetSequential = Sequential
End Function
单独运行时效果很好:
cscript testsequence.vbs
但是当同时运行几次时,不能保证获得唯一的序列号。这在启动这样的批处理文件时很明显:
for /l %%x in (1, 1, 25) do start cscript testsequence.vbs
由于返回相同的序列值(文件已存在)而在创建结果_?。txt文件时产生异常失败。
所以问题是如何锁定表更新操作?
提前致谢。
答案 0 :(得分:1)
您似乎认为脚本中的更新和读取将是原子的:
sequence
sequence
sequence
sequence
sequence
sequence
sequence
sequence
这样A和B将读取相同的值,尽管两个进程都会增加它。
您需要将自己的陈述放在transaction并使用适当的isolation level。