如何将两个For Each循环保持在同一级别

时间:2014-05-09 10:00:26

标签: vb.net

对于每个产品数量,我都有一个数组,我也希望同时为数组中的每个产品ID传递一个。我希望id和qty同时插入一个表,同一级别...我不能嵌套这样做,帮助???

Dim strSQLCommand As String
For Each productQtys In productQty
    For Each productIds In productId
        strSQLCommand = "INSERT INTO Orders(SessionID, productID, qty, orderDate) " & _
            "Values ('" & strSessionID & "','" & productIds & "','" & productQtys & "','" & dateOfOrder & "');"
        Dim objOleDbConnection As System.Data.OleDb.OleDbConnection
        objOleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation)
        objOleDbConnection.Open()
        Dim objOleDbCommand As System.Data.OleDb.OleDbCommand
        objOleDbCommand = New System.Data.OleDb.OleDbCommand(strSQLCommand, objOleDbConnection)
        objOleDbCommand.ExecuteNonQuery()
        objOleDbConnection.Close()
    Next
Next

2 个答案:

答案 0 :(得分:1)

尝试使用索引来指出ID和数量。这样,您就可以在相同的行级别内获得ID和数量。

实施例

Dim myListID As List(Of Integer)
Dim myListQty As List(Of Integer)
Dim id As Integer
Dim qty As Integer

myListID.Add(1)
myListID.Add(2)
myListID.Add(3)

myListQty.Add(123)
myListQty.Add(456)
myListQty.Add(789)

For ctr As Integer = 1 To myListID.Count
    id = myListID.Item(ctr)
    qty = myListQty.Item(ctr)
    '
    ' Insert here your SQL command
    '
Next 

答案 1 :(得分:1)

你可以为一个使用for循环,为另一个使用手动递增的数组,如下所示: 如果这些集合(或数组)具有相同数量的元素:

Dim strSQLCommand As String Dim intProductIdIndex as integer=0 For Each productQtys In productQty strSQLCommand = "INSERT INTO Orders(SessionID, productID, qty, orderDate) " & _ "Values ('" & strSessionID & "','" & productId(intProductIdIndex) & "','" & productQtys & "','" & dateOfOrder & "');" Dim objOleDbConnection As System.Data.OleDb.OleDbConnection objOleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation) objOleDbConnection.Open() Dim objOleDbCommand As System.Data.OleDb.OleDbCommand objOleDbCommand = New System.Data.OleDb.OleDbCommand(strSQLCommand, objOleDbConnection) objOleDbCommand.ExecuteNonQuery() objOleDbConnection.Close() intProductIdIndex = intProductIdIndex + 1 Next