본문 바로가기
#모바일 [Mobile]/iOS

[iOS] SQLite (SQLite With Swift Tutorial: Getting Started)

by cy_mos 2019. 10. 25.
반응형
[iOS] SQLite (SQLite With Swift Tutorial: Getting Started)

 

SQLite는 MySQL나 PostgreSQL와 같은 데이터베이스 관리 시스템이지만, 서버가 아니라 응용 프로그램에 넣어 사용하는 비교적 가벼운 데이터베이스이다. 영어권에서는 '에스큐엘라이트(ˌɛskjuːɛlˈlaɪt)' 또는 '시퀄라이트(ˈsiːkwəl.laɪt)'라고 읽는다. 일반적인 RDBMS에 비해 대규모 작업에는 적합하지 않지만, 중소 규모라면 속도에 손색이 없다.

 

또한 API는 단순히 라이브러리를 호출하는 것만 있으며, 데이터를 저장하는 데 하나의 파일만을 사용하는 것이 특징이다. 버전 3.3.8에서는 풀텍스트 검색 기능을 가진 FTS1 모듈이 지원된다. 컬럼을 삭제하거나 변경하는 것 등이 제한된다.

 

SQLite (/ˌɛsˌkjuːˌɛlˈaɪt//ˈsiːkwəˌlaɪt/) is a relational database management system (RDBMS) contained in a C library. In contrast to many other database management systems, SQLite is not a client–server database engine. Rather, it is embedded into the end program.

 

SQLite is ACID-compliant and implements most of the SQL standard, generally following PostgreSQL syntax. However, SQLite uses a dynamically and weakly typed SQL syntax that does not guarantee the domain integrity. This means that one can, for example, insert a string into a column defined as an integer. SQLite will attempt to convert data between formats where appropriate, the string "123" into an integer in this case, but does not guarantee such conversions, and will store the data as-is if such a conversion is not possible.

 

SQLite is a popular choice as embedded database software for local/client storage in application software such as web browsers. It is arguably the most widely deployed database engine, as it is used today by several widespread browsers, operating systems, and embedded systems (such as mobile phones), among others. SQLite has bindings to many programming languages.

 

📚 SQLite 장점과 단점

👍 장점

- 다양한 운영체제 환경에서 사용할 수 있습니다.

- SQLite로 인해 생성되는 각 데이터베이스는 하나의 파일로 구성되어 관리가 편리합니다.

👎 단점

- 주로 개발용 및 소규모 프로젝트에서 사용되는 데이터베이스이므로 대규모의 데이터를 처리하는 프로젝트에는 적합하지 않습니다.

- 클러스터 및 수평 확장 솔루션을 제공하지 않습니다.

- 최소한의 구성 및 튜닝 옵션을 제공하므로 하위 호환성에 대한 문제가 발생합니다.


📄 SQLite Source Code by Swift

SQLite.zip
0.02MB

✏️ SQLite Create Source Code by Swift

/// Open SQLite Database
private func openSQLite(path: String) -> OpaquePointer? {
    
    var database: OpaquePointer? = nil
    
    // Many of the SQLite functions return an Int32 result code. Most of these codes are defined as constants in the SQLite library. For example, SQLITE_OK represents the result code 0.
    guard sqlite3_open(path, &database) == SQLITE_OK else {
        print("‼️ Unable to open database.")
        return nil
    }
    
    // Success Open SQLite Database
    print("✅ Successfully opened connection to database at \(path)")
    return database
}

/// Create SQLite Database Table
private func createSQLiteTable(database: OpaquePointer, statement: String) -> Bool {
    
    var createStatement: OpaquePointer? = nil
    
    // You must always call sqlite3_finalize() on your compiled statement to delete it and avoid resource leaks.
    defer { sqlite3_finalize(createStatement) }
        
    guard sqlite3_prepare_v2(database, statement, EOF, &createStatement, nil) == SQLITE_OK else {
        print("‼️ CREATE TABLE statement could not be prepared.")
        return false
    }
    
    // sqlite3_step() runs the compiled statement.
    if sqlite3_step(createStatement) == SQLITE_DONE {
        print("✅ Success, Contact table created.")
    } else {
        print("‼️ Fail, Contact table could not be created.")
    }
    
    return true
}

✏️ SQLite Insert Source Code by Swift

/// Insert Data into SQLite Database Table
private func insertSQLiteTable(database: OpaquePointer, statement: String) -> Bool {
    
    var insertStatement: OpaquePointer? = nil
    
    // You must always call sqlite3_finalize() on your compiled statement to delete it and avoid resource leaks.
    defer { sqlite3_finalize(insertStatement) }
    
    guard sqlite3_prepare_v2(database, statement, EOF, &insertStatement, nil) == SQLITE_OK else {
        print("‼️ Insert TABLE statement could not be prepared.")
        return false
    }
    
    // Use the sqlite3_step() function to execute the statement and verify that it finished.
    if sqlite3_step(insertStatement) == SQLITE_DONE {
        print("✅ Success, Insert Data.")
    } else {
        print("‼️ Fail, Insert Data.")
    }
    
    return true
}

✏️ SQLite Query Source Code by Swift

/// Implement Query SQLite
private func qeurySQLite(database: OpaquePointer, statment: String) -> Bool {
    
    var queryStatment: OpaquePointer? = nil
    
    // You must always call sqlite3_finalize() on your compiled statement to delete it and avoid resource leaks.
    defer { sqlite3_finalize(queryStatment) }
    
    guard sqlite3_prepare_v2(database, statment, EOF, &queryStatment, nil) == SQLITE_OK else {
        print("‼️ Query statement could not be prepared.")
        return false
    }
    
    while sqlite3_step(queryStatment) == SQLITE_ROW {
        
        let id = sqlite3_column_int(queryStatment, 0)
        let name = sqlite3_column_text(queryStatment, 1)
        
        print("→ \(id) | \(String(describing: name))")
    }
    
    return true
}

🚀 REFERENCE

 

SQLite - Wikipedia

From Wikipedia, the free encyclopedia Jump to navigation Jump to search Serverless relational database management system (RDBMS) SQLite (,[4][5] [6]) is a relational database management system (RDBMS) contained in a C library. In contrast to many other dat

en.wikipedia.org

 

SQLite Browser - SQL Online

Chart.test Label Graphs

sqliteonline.com

 

SQLite With Swift Tutorial: Getting Started

In this SQLite with swift tutorial, learn how to utilise the SQLite database with your Swift projects, including inserting, updating and deleting rows.

www.raywenderlich.com

 

SQLite를 사용해야 하는 이유

모든 비즈니스 애플리케이션의 내부에는 구조적 데이터를 저장하고 사용하는 나름의 방법이 구현돼 있다. 클라이언트 측 앱이든 웹 프론트엔드를 사용하는 앱이든 에지 디바이스 앱이든 대부분의 경우 내장 데이터베이스가 필요하다.이런 경우를 위해 설계된 SQLite는 내장 가능한 오픈소스 데이터베이스로, C로 작성됐으며 일반적인 SQL로 쿼리가 가능하다. SQLite는 킬로바이트의 데이터를 저장하든 수 기가바이트의 블롭(blob)을 저장하든 빠른 속도와 이식성

www.itworld.co.kr

반응형

댓글