2

以下代码片段是否有更好的解决方案(使用更少的代码)。这是我发现自己在 VB6 中做了很多的事情,并希望能减少它。

据我了解,Connection.Execute 不起作用

    SQL = "SELECT SomeID FROM TableA"
    RecordSet.Open SQL, Connection, adOpenStatic, adLockOptimistic, adCmdText
    SomeID = RecordSet.Fields(0).Value
    RecordSet.Close

    SQL = "SELECT AnotherID FROM TableB"
    RecordSet.Open SQL, Connection, adOpenStatic, adLockOptimistic, adCmdText
    AnotherID = RecordSet.Fields(0).Value
    RecordSet.Close

这不是一个功能问题,只是想看看是否有更整洁的方式。

4

3 回答 3

1

RecordSet.Open()和的默认参数Connection.Execute()是:

  • adOpenForwardOnly
  • adLockReadOnly

您使用不同的设置,但在您的情况下没有明显的理由不使用默认设置。

我不知道你为什么认为这Connection.Execute()不起作用,特别是因为你似乎有静态 SQL:

Function FetchOneField(Connection, SQL)
  With Connection.Execute(SQL)
    FetchOneField = .Fields(0).Value
    .Close
  End With
End Function

SomeID    = FetchOneField(Connection, "SELECT SomeID FROM TableA")
AnotherID = FetchOneField(Connection, "SELECT AnotherID FROM TableB")

' or, not expressed as a function (not less lines, but "tidier" nevertheless)'
With Connection.Execute("SELECT SomeID FROM TableA")
  SomeID = .Fields(0).Value
  .Close
End With
于 2009-03-16T10:52:53.607 回答
0

假设您每个查询有 1 条记录,您可以这样做

SQL = "SELECT TableA.SomeID, TableB.AnotherID FROM TableA, TableB"
RecordSet.Open SQL, Connection, adOpenStatic, adLockOptimistic, adCmdText
SomeID = RecordSet.Fields(0).Value
AnotherID = RecordSet.Fields(1).Value
RecordSet.Close
于 2009-03-16T12:36:12.533 回答
0

Connection.Execute 应该工作。这对我有用:

  Const Sql1 As String = "SELECT SomeID FROM TableA"
  SomeID = Connection.Execute(Sql1)(0).Value

  Const Sql2 As String = "SELECT AnotherID FROM TableB"
  AnotherID = Connection.Execute(Sql2)(0).Value

...虽然我个人会封装那些Connection.Execute我可以明确地从连接池等释放连接的行。

于 2009-03-16T13:28:39.363 回答