'Inserts the data to 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).
Sub InsertMaps(SQL As SQL, TableName As String, ListOfMaps As List, UsingAutoIncrement As Boolean)
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.")
ToastMessageShow("Same Map found twice in list. Each item in the list should include a different map object.", True)
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
sb.Append("INSERT INTO [" & TableName & "] (")
Dim m As Map
Dim StringArgs() As String
m = ListOfMaps.Get(i1)
For i2 = 0 To m.Size - 1
Dim col As String
Dim value As Object
col = m.GetKeyAt(i2)
value = m.GetValueAt(i2)
If i2 > 0 Then
columns.Append(", ")
values.Append(", ")
End If
columns.Append("[").Append(col).Append("]")
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)
Dim returnval As Int
If UsingAutoIncrement Then
'Additional code to obtain the ID of the newly inserted auto increment row
'and append it to the map, this will then be available from the calling module.
sb.Initialize
sb.Append("SELECT last_insert_rowid() as ID from ").Append(TableName)
returnval=SQL.ExecQuerySingleResult(sb.ToString)
m.Put("ID", returnval)
ListOfMaps.Set(i1,m)
Log(returnval)
End If
Next
SQL.TransactionSuccessful
Catch
ToastMessageShow(LastException.Message, True)
Log(LastException)
End Try
SQL.EndTransaction
End Sub