【问题标题】:table update locking from vbscript来自 vbscript 的表更新锁定
【发布时间】:2013-02-07 05:07:06
【问题描述】:

从这样的表中:

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文件时由于返回相同的序列值(文件已存在)而产生异常失败。

那么问题是如何锁定表更新操作?

提前致谢。

【问题讨论】:

    标签: mysql vbscript locking


    【解决方案1】:

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

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

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

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

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

    您需要将您的陈述放入transaction 并使用适当的isolation level

    【讨论】:

    • 谢谢,现在只要在 cn.Execute "start transaction" 和 cn.Execute "commit" 之间加上 update-select 操作就可以正常工作了。不知道我应该在哪里放一个 cn.Execute “回滚”...
    • 可能无处可去。 rollback 取消事务并回滚到目前为止事务已更改的所有内容。因此得名。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-29
    • 2013-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多