简体   繁体   English

在 VBScript 中的 ADO 中使用事务和参数

[英]Using transcations and parameters in ADO in VBScript

I'm a bit stuck with parameters and transactions in ADO, in VBScript and Access.我在 ADO、VBScript 和 Access 中的参数和事务有点卡住。 Basically, I'm working through a massive loop and writing the results to a database, so I need to wrap it in a transaction otherwise it takes ages.基本上,我正在处理一个巨大的循环并将结果写入数据库,所以我需要将它包装在一个事务中,否则它需要很长时间。

I've written the below script which works for a single parameter, (although this seems a bit of a long way of doing it, so if anyone knows a shorter way, please shout).我编写了下面的脚本,它适用于单个参数,(虽然这似乎有点长的路要走,所以如果有人知道更短的方法,请大喊)。 However I can't work out how to expand this to two parameters:但是我不知道如何将其扩展到两个参数:

objConn.BeginTrans  

  set oParm = CreateObject("ADODB.Parameter")
    oParm.Value = ""
    oParm.Type = 200
    oParm.Direction = 1
    oParm.Size = 100

  Set oCmd = CreateObject("ADODB.Command")
    oCmd.ActiveConnection = objConn
    oCmd.commandText = "INSERT INTO table (field) VALUES (?)"
    oCmd.commandType = 1
    oCmd.Parameters.Append oParm


    'Big loop here that goes through lots of lines.

      oCmd.Execute ,"Field",1

    'Loop 

objConn.CommitTrans

For example, if I wanted to expand this to:例如,如果我想将其扩展为:

oCmd.commandText = "INSERT INTO table (field1, field2) VALUES (?,?)"

I can't figure out what I do with my parameters.我不知道我用我的参数做了什么。 I'm sure I'm just being stupid here and not quite following how these work.我确定我只是在这里很愚蠢,并没有完全遵循这些工作原理。

I've never tried passing parameter values through the Execute method, so I can't quite say what's wrong.我从来没有尝试过通过Execute方法传递参数值,所以我不能完全说出问题所在。 I will say that the documentation states that the second argument should be an array of values, so maybe if you tried Array("Field1Val", "Field2Val") , that would work.我会说文档说明第二个参数应该是一个值数组,所以如果你尝试过Array("Field1Val", "Field2Val") ,那可能会奏效。

What I usually do is give each parameter a name, then you can reference it within your loop to change its value.我通常做的是给每个参数一个名字,然后你可以在你的循环中引用它来改变它的值。 You can use any name you like, as long each parameter has a unique name.您可以使用任何您喜欢的名称,只要每个参数都有一个唯一的名称。 As an example:举个例子:

' Sometime before your loop
oParm.Name = "foobar"

' Start loop
    oCmd.Parameters("foobar").Value = "someValue"
    oCmd.Execute , , 1
' End loop

As far as shortening the code, the only suggestion I can make is using the CreateParameter method to, well, create the parameter.至于缩短代码,我能提出的唯一建议是使用CreateParameter方法来创建参数。 That will allow you to set all the relevant properties on one line.这将允许您在一行上设置所有相关属性。

Set oParm = oCmd.CreateParameter("foobar", 200, 1, 100)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM