使用 isTransaction 使用 FMDB 在数据库中插入三千个字符串数据
Inserting three thousand string data in database with FMDB using isTransaction
我试图在首次启动时向我的应用程序中插入大约 3000 个字符串数据。我遇到的问题是插入部分花费了大约 15-20 秒的时间。我查找了使 isTransaction 方法更快的方法,但我不知道如何使用它。我在网上尝试了很多例子,但似乎不太适合我的情况。非常感谢您的帮助。
func insertWordData() {
if openDatabase() {
if let path = Bundle.main.path(forResource: "messagesToRead", ofType: "json") {
var query = ""
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
let jsonObj = JSON(data: data)
if jsonObj != JSON.null {
for (_, jsonObj) in jsonObj {
let WordString = jsonObj["FIELD1"]
let WordDefinition = jsonObj["FIELD2"]
query += "insert into words (\(field_WordID), \(field_WordString), \(field_WordDefinition)) values (null, '\(WordString)', '\(WordDefinition)');"
}
}
if !database.executeStatements(query) {
print("Failed to insert initial data into the database.")
print(database.lastError(), database.lastErrorMessage())
}
else {
//print(words)
}
} catch let error {
print(error.localizedDescription)
}
} else {
print("Invalid filename/path.")
}
database.close()
}
}
没关系,问题已解决我所要做的就是在 for 循环之前添加 database.beginTransaction() 并在 database.close() 之前添加 database.commit()。速度从 15-20 秒变为 0.5 秒
我试图在首次启动时向我的应用程序中插入大约 3000 个字符串数据。我遇到的问题是插入部分花费了大约 15-20 秒的时间。我查找了使 isTransaction 方法更快的方法,但我不知道如何使用它。我在网上尝试了很多例子,但似乎不太适合我的情况。非常感谢您的帮助。
func insertWordData() {
if openDatabase() {
if let path = Bundle.main.path(forResource: "messagesToRead", ofType: "json") {
var query = ""
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
let jsonObj = JSON(data: data)
if jsonObj != JSON.null {
for (_, jsonObj) in jsonObj {
let WordString = jsonObj["FIELD1"]
let WordDefinition = jsonObj["FIELD2"]
query += "insert into words (\(field_WordID), \(field_WordString), \(field_WordDefinition)) values (null, '\(WordString)', '\(WordDefinition)');"
}
}
if !database.executeStatements(query) {
print("Failed to insert initial data into the database.")
print(database.lastError(), database.lastErrorMessage())
}
else {
//print(words)
}
} catch let error {
print(error.localizedDescription)
}
} else {
print("Invalid filename/path.")
}
database.close()
}
}
没关系,问题已解决我所要做的就是在 for 循环之前添加 database.beginTransaction() 并在 database.close() 之前添加 database.commit()。速度从 15-20 秒变为 0.5 秒