'Inserts or Update the data to/in the table.
'ListOfMaps - A list with maps as items. Each map represents a record where the map keys are the columns names
'and the maps values are the values.
'Note that you should create a new map for each record (this can be done by calling Dim to redim the map).
Public Sub InsertOrUpdateMaps(SQL As SQL, TableName As String, Key As String, ListOfMaps As List)
Dim sb, columns, values As StringBuilder
'Small check for a common error where the same map is used in a loop
If ListOfMaps.Size > 1 And ListOfMaps.Get(0) = ListOfMaps.Get(1) Then
Log("Same Map found twice in list. Each item in the list should include a different map object.")
Return
End If
SQL.BeginTransaction
Try
For i1 = 0 To ListOfMaps.Size - 1
sb.Initialize
columns.Initialize
values.Initialize
Dim listOfValues As List
listOfValues.Initialize
Dim m As Map = ListOfMaps.Get(i1)
Dim value_exists As Map = ExecuteMap(SQL, "SELECT " & EscapeField(Key) & " FROM " & EscapeField(TableName) & " WHERE " & EscapeField(Key) & " = '" & m.Get(Key) & "'", Null)
Log("value_exists: " & value_exists)
If value_exists.IsInitialized=False Then
sb.Append("INSERT INTO [" & TableName & "] (")
For Each col As String In m.Keys
Dim Value As Object = m.Get(col)
If listOfValues.Size > 0 Then
columns.Append(", ")
values.Append(", ")
End If
columns.Append(EscapeField(col))
values.Append("?")
listOfValues.Add(Value)
Next
sb.Append(columns.ToString).Append(") VALUES (").Append(values.ToString).Append(")")
If i1 = 0 Then Log("InsertMaps (first query out of " & ListOfMaps.Size & "): " & sb.ToString)
SQL.ExecNonQuery2(sb.ToString, listOfValues)
Else
sb.Append("UPDATE [" & TableName & "] SET ")
For Each col As String In m.Keys
If listOfValues.Size>0 Then
sb.Append(",")
End If
sb.Append(EscapeField(col)).Append("=?")
listOfValues.Add(m.Get(col))
Next
sb.Append(" WHERE [" & Key & "] = ?")
listOfValues.Add(value_exists.Get(Key))
If i1 = 0 Then Log("UpdateMaps (first query out of " & ListOfMaps.Size & "): " & sb.ToString)
SQL.ExecNonQuery2(sb.ToString, listOfValues)
End If
Next
SQL.TransactionSuccessful
Catch
Log(LastException)
#If B4i OR B4J
SQL.Rollback
#End If
End Try
#If B4A
SQL.EndTransaction
#End If
End Sub