I am trying to insert about 10000 data into my database. Check below function for code. It takes about a minute to insert all data. Now I already added block in transaction but do I need to Commit it or it manages automatically. How can I write it in below code?
func insertDataToDB(objects: [DataModel]) {
removeAllData()
createSchemaForData()
print("Start Inserting Connectors \(Date())")
let stmt = try? db.prepare("INSERT INTO product (connectorId, deviceId, current, status, cost, voltage, power, type, method, mode) VALUES (?,?,?,?,?,?,?,?,?,?)")
do {
try db.transaction {
for product in objects {
try stmt?.run(product.connectorId!, product.deviceId!, product.current, product.status, product.cost, product.voltage, product.power, product.type!, product.method!, product.mode)
}
}
} catch {
print("Failed Inserting connectors: \(error.localizedDescription)")
}
print("End Inserting Connectors \(Date())")
}
removeAllData()
Will remove all data from db before inserting.
createSchemaForData()
Will create schema if required.
struct product {
static let table = Table("product")
static let connectorId = Expression<String>("connectorId")
static let deviceId = Expression<String>("deviceId")
static let current = Expression<Double?>("current")
static let status = Expression<String?>("status")
static let cost = Expression<Double?>("cost")
static let voltage = Expression<Double?>("voltage")
static let power = Expression<Double?>("power")
static let type = Expression<String?>("type")
static let method = Expression<String?>("method")
static let mode = Expression<String?>("mode")
}