FMDBを介してiOSモバイルアプリケーションにSQLLiteを接続するタスクに直面して、ロシア語で関連するガイドが見つかりませんでした。 Swiftの場合はさらにそうです。 この記事では、修正を試みます。
このガイドでは、objective-cのファイルが使用されるため、SwiftのFMDBポートを待つ必要はありません。
FMDBは
こちらからダウンロードできます。
FMDBには3つの主要なクラスがあります。
FMDatabase-SQLiteデータを表します。 SQLステートメントの実行に使用されます。
FMResultSet-FMDatabaseによるクエリ実行の結果を提示します。
FMDatabaseQueue-複数のスレッドでクエリと更新を実行する場合、このクラスを使用できます。 パラグラフ8の例。
データベースを操作する前に、データベースを開いておく必要があります。 データベースを開いたり作成したりするための十分なリソースまたは許可がない場合、開くことができません。
if (![db open]) { [db release]; return; }
手順:1)プロジェクト設定に「libsqlite3」標準ライブラリを追加し、FMDBファイルをプロジェクトにコピーします。 (はい、それらはObjective-Cにあります)。
2) 「FMDB-Bridging-Header.h」という新しいファイルを作成します。 「Bridging-Header.h」内に、#import「FMDB.h」と記述します。
3) Build Settings-> Swift Compiler-Code Generationに移動し、「Objective-C Bridging Header」に追加します:FMDB-Bridging-Header.h。
ファイルがプロジェクトのフォルダーにある場合、次のようになります:FOLDER_NAME / FMDB-Bridging-Header.h
4) SQLiteデータベースをプロジェクトにコピーします。 このガイドでは、「tempdb.sqlite」という名前を使用し、テーブルを1つだけ使用します。
CREATE TABLE test_tb(test_id INTEGER PRIMARY KEY AUTOINCREMENT、name TEXT、keywordtext TEXT)
5) AppDelegate.swiftのクラスAppDelegateに次の変数を追加します。var dbFilePath:NSString = NSString()
例:
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var navi: UINavigationController? var dbFilePath: NSString = NSString() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { ....
6)このメソッドをAppDelegate.swiftのクラスAppDelegateに追加します。
7) AppDelegate.swiftのfuncアプリケーションを呼び出します。
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { if self.initializeDb() { NSLog("Successful db copy") }
8)この例では、FMDBを使用してUITableViewControllerデータを操作しています:
import UIKit class SecondViewController: UIViewController {
9) FMDatabaseQueueを介したマルチストリームFMDBを使用したわずかに異なるチップ。
var queue: FMDatabaseQueue? func testDatabaseQueue() { let documentsFolder = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String let databasePath = documentsFolder.stringByAppendingPathComponent("test.sqlite") queue = FMDatabaseQueue(path: databasePath)
// 5行挿入します
queue?.inTransaction() { db, rollback in for i in 0 ..< 5 { if !db.executeUpdate("insert into test (a) values (?)", withArgumentsInArray: ["Row \(i)"]) { println("insert \(i) failure: \(db.lastErrorMessage())") rollback.initialize(true) return } } }
//行を挿入しようとしますが、意図的に間違いを犯し、正しくロールバックすることを確認します
queue?.inTransaction() { db, rollback in for i in 5 ..< 10 { let success = db.executeUpdate("insert into test (a) values (?)", withArgumentsInArray: ["Row \(i)"]) if !success { println("insert \(i) failure: \(db.lastErrorMessage())") rollback.initialize(true) return } if (i == 7) { rollback.initialize(true) } } }
//最初の5行のみが存在することを確認します
queue?.inDatabase() { db in if let rs = db.executeQuery("select * from test", withArgumentsInArray:nil) { while rs.next() { println(rs.resultDictionary()) } } else { println("select failure: \(db.lastErrorMessage())") } }
//テーブルを削除します
queue?.inDatabase() { db in let success = db.executeUpdate("drop table test", withArgumentsInArray:nil) if !success { println("table drop failure: \(db.lastErrorMessage())") return } } }
10)スナックの標準。 Swift2でexecuteUpdate(値:)クラスを使用する:
do { let identifier = 42 let name = "Liam O'Flaherty (\"the famous Irish author\")" let date = NSDate() let comment: String? = nil try db.executeUpdate("INSERT INTO authors (identifier, name, date, comment) VALUES (?, ?, ?, ?)", values: [identifier, name, date, comment ?? NSNull()]) } catch { print("error = \(error)") }
キューを使用する:
queue.inTransaction { db, rollback in do { try db.executeUpdate("INSERT INTO myTable VALUES (?)", values: [1]) try db.executeUpdate("INSERT INTO myTable VALUES (?)", values: [2]) try db.executeUpdate("INSERT INTO myTable VALUES (?)", values: [3]) if whoopsSomethingWrongHappened { rollback.memory = true return } try db.executeUpdate("INSERT INTO myTable VALUES (?)", values: [4]) } catch { rollback.memory = true print(error) } }
標準の説明の例:
let documents = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false) let fileURL = documents.URLByAppendingPathComponent("test.sqlite") let database = FMDatabase(path: fileURL.path) if !database.open() { print("Unable to open database") return } do { try database.executeUpdate("create table test(x text, y text, z text)", values: nil) try database.executeUpdate("insert into test (x, y, z) values (?, ?, ?)", values: ["a", "b", "c"]) try database.executeUpdate("insert into test (x, y, z) values (?, ?, ?)", values: ["e", "f", "g"]) let rs = try database.executeQuery("select x, y, z from test", values: nil) while rs.next() { let x = rs.stringForColumn("x") let y = rs.stringForColumn("y") let z = rs.stringForColumn("z") print("x = \(x); y = \(y); z = \(z)") } } catch let error as NSError { print("failed: \(error.localizedDescription)") } database.close()
何かがうまくいかない場合は、書いて、私は助けようとします。