我是 VBA 新手,我想通過 shell 多次查詢 MongoDB 資料庫。但是,當查詢的輸出為空白時(因為它在資料庫中不存在),我似乎無法通過同一個 shell 實體執行另一個命令。有人為什么會出現這種情況以及如何解決它?
Dim wsh As New WshShell
Dim proc As WshExec
Dim i As Integer
Dim result As String
Set proc = wsh.Exec("mongo")
proc.StdIn.WriteLine "use mydb"
For i = 1 To 4
If i = 3 Then
proc.StdIn.WriteLine "db.mycollection.find({'field': 'something non-existent'})"
Else
proc.StdIn.WriteLine "db.mycollection.find({'field': '" & i & "'})"
End If
result = proc.StdOut.ReadLine
Debug.Print i
Debug.Print result
Next i
proc.StdIn.WriteLine "quit()"
出口:
1
{something}
2
{something}
3
4
所以對于迭代 3 和 4,我只得到一個空行,并且 shell 視窗最后沒有關閉。如果您洗掉 if 陳述句(以便查詢確實找到某些內容),則每次迭代都會顯示一個結果,并且 shell 將在最后關閉。
uj5u.com熱心網友回復:
我找到了解決我的問題的方法。問題在于,如果查詢結果為空白或 null 并且您嘗試讀取 stdout 的行,則指標將移動到流的末尾。這意味著讀取“檔案”。
基本上,我需要確保它永遠不會回傳空白/空值。所以,我這樣做了:
Dim wsh As New WshShell
Dim proc As WshExec
Dim i As Integer
Dim check As String
Dim result As String
Set proc = wsh.Exec("mongo")
proc.StdIn.WriteLine "use mydb"
For i = 1 To 4
proc.StdIn.WriteLine "db.mycollection.find({'field': '" & i & "'}).count()"
check = proc.StdOut.ReadLine
If CInt(check) > 0 Then ' Now you are sure it will result in something.
proc.StdIn.WriteLine "db.mycollection.find({'field': '" & i & "'})"
result = proc.StdOut.ReadLine
End If
Next i
proc.StdIn.WriteLine "quit()"
proc.StdOut.ReadLine
也許這不是擺脫“StdOut.AtEndOfStream”問題的最佳或最優雅的方法,但它是一種簡單的方法。這樣您就不必呼叫單獨的腳本和/或使用單獨的輸入/輸出檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/485027.html
