Swift와 SQLite 연동

2020. 5. 12. 19:43아이폰 개발

외부에서 만들어진 SQLite 파일을 사용하기 위해서는 일단 번들 내에 있는 SQLite 파일을 도규먼트 폴더로 복사를 해야 한다.

안드로이드/iOS 앱을 동시 개발할 때, 기본적으로 저장되어야 하는 데이터를 SQLite 파일어 저장을 하면 양쪽 앱에서 같이 사용할 수 있는 장점이 된다.

func copyDatabaseIfNeeded() {
        // Move database file from bundle to documents folder
        
        let fileManager = FileManager.default
        
        let documentsUrl = fileManager.urls(for: .documentDirectory,
                                                    in: .userDomainMask)
        
        guard documentsUrl.count != 0 else {
            return // Could not find documents URL
        }
        
        let finalDatabaseURL = documentsUrl.first!.appendingPathComponent("SQL.sqlite")
    
        if !( (try? finalDatabaseURL.checkResourceIsReachable()) ?? false) {
            print("DB does not exist in documents folder")
            
            let documentsURL = Bundle.main.resourceURL?.appendingPathComponent("SQL.sqlite")
            
            do {
                  try fileManager.copyItem(atPath: (documentsURL?.path)!, toPath: finalDatabaseURL.path)
                  } catch let error as NSError {
                    print("Couldn't copy file to final location! Error:\(error.description)")
            }

        } else {
            print("Database file found at path: \(finalDatabaseURL.path)")
        }
    
    }

https://gist.github.com/rd13/320b3fed4d5f10ab8ea833b3f9818980

 

Copy database file from bundle to documents in Swift 3

Copy database file from bundle to documents in Swift 3 - .swift

gist.github.com

기본적으로 Swift에서도 C 형식의 저수준 함수를 사용하면 SQLite 사용이 가능하지만, Swift에서 쉽게 사용할 수 있도록 만들어진 Wrapper 클래스나 라이브러리를 사용하는 것도 좋은 방법이다.

import SQLite

let db = try Connection("path/to/db.sqlite3")

let users = Table("users")
let id = Expression<Int64>("id")
let name = Expression<String?>("name")
let email = Expression<String>("email")

try db.run(users.create { t in
    t.column(id, primaryKey: true)
    t.column(name)
    t.column(email, unique: true)
})
// CREATE TABLE "users" (
//     "id" INTEGER PRIMARY KEY NOT NULL,
//     "name" TEXT,
//     "email" TEXT NOT NULL UNIQUE
// )

let insert = users.insert(name <- "Alice", email <- "alice@mac.com")
let rowid = try db.run(insert)
// INSERT INTO "users" ("name", "email") VALUES ('Alice', 'alice@mac.com')

for user in try db.prepare(users) {
    print("id: \(user[id]), name: \(user[name]), email: \(user[email])")
    // id: 1, name: Optional("Alice"), email: alice@mac.com
}
// SELECT * FROM "users"

let alice = users.filter(id == rowid)

try db.run(alice.update(email <- email.replace("mac.com", with: "me.com")))
// UPDATE "users" SET "email" = replace("email", 'mac.com', 'me.com')
// WHERE ("id" = 1)

try db.run(alice.delete())
// DELETE FROM "users" WHERE ("id" = 1)

try db.scalar(users.count) // 0
// SELECT count(*) FROM "users"

https://github.com/stephencelis/SQLite.swift

 

stephencelis/SQLite.swift

A type-safe, Swift-language layer over SQLite3. Contribute to stephencelis/SQLite.swift development by creating an account on GitHub.

github.com

 

https://www.raywenderlich.com/6620276-sqlite-with-swift-tutorial-getting-started

 

SQLite With Swift Tutorial: Getting Started

In this SQLite with Swift tutorial, you’ll learn to use a SQLite database with Swift projects by creating tables and inserting, updating and deleting rows.

www.raywenderlich.com