0

从这样的表:

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

由于返回相同的序列值(文件已存在),在创建 result_?.txt 文件时会产生异常失败。

所以问题是如何锁定表更新操作?

提前致谢。

4

1 回答 1

1

您似乎认为脚本中的更新和读取将是原子的:

  • 进程 A 更新sequence
  • 进程 A 读取sequence
  • 进程 B 更新sequence
  • 进程 B 读取sequence

然而,MySQL 默认启用了自动提交,因此每个语句都是自己运行的,来自并发进程的查询可能会变得混合:

  • 进程 A 更新sequence
  • 进程 B 更新sequence
  • 进程 B 读取sequence
  • 进程 A 读取sequence

这样 A 和 B 将读取相同的值,尽管两个进程都会增加它。

您需要将您的语句放在一个事务中并使用适当的隔离级别

于 2013-02-06T21:07:06.600 回答