Swiftを使用してXcodeでFMDB経由でSQLiteをiOSモバイルアプリに接続します

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に追加します。



 // MARK: - FMDB let DATABASE_RESOURCE_NAME = "tempdb" let DATABASE_RESOURCE_TYPE = "sqlite" let DATABASE_FILE_NAME = "tempdb.sqlite" func initializeDb() -> Bool { let documentFolderPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String let dbfile = "/" + DATABASE_FILE_NAME; self.dbFilePath = documentFolderPath.stringByAppendingString(dbfile) let filemanager = NSFileManager.defaultManager() if (!filemanager.fileExistsAtPath(dbFilePath) ) { let backupDbPath = NSBundle.mainBundle().pathForResource(DATABASE_RESOURCE_NAME, ofType: DATABASE_RESOURCE_TYPE) if (backupDbPath == nil) { return false } else { var error: NSError? let copySuccessful = filemanager.copyItemAtPath(backupDbPath, toPath:dbFilePath, error: &error) if !copySuccessful { println("copy failed: \(error?.localizedDescription)") return false } } } return true }
      
      





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 { // MARK: - .H @IBOutlet var dataTable: UITableView? var dataArray:[MultiField] = [] // MARK: - .M required init(coder: NSCoder) { fatalError("NSCoding not supported") } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) // Custom initialization } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = "FMDB Using Swift" let mainDelegate: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate // initialize FMDB let db: FMDatabase = FMDatabase(path:mainDelegate.dbFilePath) if (db.open() == nil) { NSLog("error opening db") } //   let addQuery = "INSERT INTO test_tb (name, keywordtext) VALUES ('excalibur', 'hot')" let addSuccessful = db.executeUpdate(addQuery, withArgumentsInArray: nil) if !addSuccessful { println("insert failed: \(db.lastErrorMessage())") } //   -  // update  let updateQuery = "UPDATE test_tb SET keywordtext = 'cool' WHERE name = 'excalibur' " let updateSuccessful = db.executeUpdate(updateQuery, withArgumentsInArray: nil) if !updateSuccessful { println("update failed: \(db.lastErrorMessage())") } // update  -  //           UITableView let mainQuery = "SELECT name, keywordtext FROM test_tb" let rsMain: FMResultSet? = db.executeQuery(mainQuery, withArgumentsInArray: []) while (rsMain!.next() == true) { let productName = rsMain?.stringForColumn("name") let keywords = rsMain?.stringForColumn("keywordtext") let multiField = MultiField(aField1: productName!, aField2: keywords!) self.dataArray.append(multiField) } //   -  //   let delQuery = "DELETE FROM test_tb WHERE name = 'excalibur' " let deleteSuccessful = db.executeUpdate(delQuery, withArgumentsInArray: nil) if !deleteSuccessful { println("delete failed: \(db.lastErrorMessage())") } //   -  // :    let rsTemp: FMResultSet? = db.executeQuery("SELECT count(*) AS numrows FROM test_tb", withArgumentsInArray: []) rsTemp!.next() let numrows = rsTemp?.intForColumn("numrows") NSLog("numrows: \(numrows)") //:    -  db.close() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - TableView DataSource func numberOfSectionsInTableView(tableView: UITableView!) -> Int { return 1 } func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { return self.dataArray.count } func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "FMDBTest") let multiField: MultiField = self.dataArray[indexPath.row] let num = indexPath.row + 1 cell.textLabel.text = "\(num). \(multiField.field1!)" cell.detailTextLabel.text = multiField.field2 return cell } // MARK: - UITableViewDelegate func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) { tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
      
      





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) //   <source lang="objectivec"> queue?.inDatabase() { db in var success = db.executeUpdate("create table test (id integer primary key autoincrement, a text)", withArgumentsInArray:nil) if !success { println("table create failure: \(db.lastErrorMessage())") return } }
      
      





// 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()
      
      





何かがうまくいかない場合は、書いて、私は助けようとします。



All Articles