以下代码段是否有更好的解决方案(使用更少的代码)。我发现自己在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
这不是一个功能问题,只是想看看是否有更整洁的方式。
答案 0 :(得分:1)
RecordSet.Open()
和Connection.Execute()
的默认参数为:
您使用不同的设置,但没有明显的理由不在您的情况下使用默认设置。
我不知道为什么你认为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
答案 1 :(得分: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
答案 2 :(得分: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
行封装在那些我可以明确表示从连接池中释放连接等的行中。