0Pricing
Objective-C iOS Development for Legacy & Enterprise Apps · 강의

FMDB를 활용한 SQLite 통합

널리 사용되는 FMDB 래퍼를 통해 Objective-C 앱에 SQLite 데이터베이스를 통합하고 데이터를 직접 조작합니다.

FMDB를 활용한 SQLite 통합은(는) CoddyKit의 무료 Objective-C iOS Development for Legacy & Enterprise Apps 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Objective-C iOS Development for Legacy & Enterprise Apps 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Objective-C iOS Development for Legacy & Enterprise Apps 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

SQLite & FMDB: An Introduction

Welcome! In this lesson, we'll explore integrating SQLite, a popular lightweight database, directly into your Objective-C applications. SQLite is embedded directly within your app, perfect for local data storage.

To make working with SQLite easier in Objective-C, we'll use FMDB, a powerful and user-friendly wrapper. It simplifies common database tasks.

Why Choose FMDB?

While you can use SQLite's C API directly, FMDB offers several advantages:

  • Object-Oriented: It provides Objective-C classes for database, result sets, and statements.
  • Simplified API: Easier to write and read than raw C code.
  • Parameter Binding: Safely handles arguments, preventing SQL injection.
  • Thread Safety: Includes FMDatabaseQueue for safe multi-threaded access.

Setting Up FMDB

To use FMDB in your project, the easiest way is via CocoaPods. Add pod 'FMDB' to your Podfile and run pod install. After installation, remember to #import "FMDB.h" in your Objective-C files.

Alternatively, you can manually drag the FMDB source files into your project.

Opening Your Database

First, you need to create or open a database file. FMDB's FMDatabase class makes this straightforward. If the file doesn't exist, it will be created.

Try running this example to open a database:

#import <Foundation/Foundation.h>
#import "FMDB.h"

int main(int argc, const char * argv[]) {
  @autoreleasepool {
    // Get the path to the app's Documents directory
    NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *dbPath = [docsPath stringByAppendingPathComponent:@"myApp.sqlite"];

    // Create an FMDatabase object
    FMDatabase *db = [FMDatabase databaseWithPath:dbPath];

    if (![db open]) {
      NSLog(@"Error: Could not open database.");
      // Always check for errors!
      return 1;
    }
    NSLog(@"Database opened successfully at: %@", dbPath);

    // Close the database when done
    [db close];
    NSLog(@"Database closed.");
  }
  return 0;
}

Creating a Table

Once the database is open, you can execute SQL commands like CREATE TABLE using executeUpdate:. This method is used for any SQL that doesn't return a result set (e.g., INSERT, UPDATE, DELETE).

Run this code to create a 'users' table:

#import <Foundation/Foundation.h>
#import "FMDB.h"

int main(int argc, const char * argv[]) {
  @autoreleasepool {
    NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *dbPath = [docsPath stringByAppendingPathComponent:@"myApp.sqlite"];
    FMDatabase *db = [FMDatabase databaseWithPath:dbPath];

    if (![db open]) { NSLog(@"Error opening db."); return 1; }

    NSString *sql = @"CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)";
    BOOL success = [db executeUpdate:sql];

    if (success) {
      NSLog(@"Table 'users' created or already exists.");
    } else {
      NSLog(@"Error creating table: %@", [db lastErrorMessage]);
    }
    [db close];
  }
  return 0;
}

Inserting Data

To add data to your table, use executeUpdate: again. FMDB is great at handling parameters, preventing SQL injection. Use ? as placeholders for your values.

See how we insert two users:

#import <Foundation/Foundation.h>
#import "FMDB.h"

int main(int argc, const char * argv[]) {
  @autoreleasepool {
    NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *dbPath = [docsPath stringByAppendingPathComponent:@"myApp.sqlite"];
    FMDatabase *db = [FMDatabase databaseWithPath:dbPath];

    if (![db open]) { NSLog(@"Error opening db."); return 1; }
    [db executeUpdate:@"CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)"];

    BOOL success1 = [db executeUpdate:@"INSERT INTO users (name, age) VALUES (?, ?)", @"Alice", @25];
    BOOL success2 = [db executeUpdate:@"INSERT INTO users (name, age) VALUES (?, ?)", @"Bob", @30];

    if (success1 && success2) {
      NSLog(@"Users inserted successfully!");
    } else {
      NSLog(@"Error inserting users: %@", [db lastErrorMessage]);
    }
    [db close];
  }
  return 0;
}

Querying Data

To retrieve data, use executeQuery:. This returns an FMResultSet object, which you can iterate through to get your results. Each row's columns can be accessed by name or index.

Let's fetch the users we just added:

#import <Foundation/Foundation.h>
#import "FMDB.h"

int main(int argc, const char * argv[]) {
  @autoreleasepool {
    NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *dbPath = [docsPath stringByAppendingPathComponent:@"myApp.sqlite"];
    FMDatabase *db = [FMDatabase databaseWithPath:dbPath];

    if (![db open]) { NSLog(@"Error opening db."); return 1; }
    [db executeUpdate:@"CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)"];
    [db executeUpdate:@"INSERT INTO users (name, age) VALUES (?, ?)", @"Charlie", @28];

    FMResultSet *rs = [db executeQuery:@"SELECT id, name, age FROM users"];
    while ([rs next]) {
      int userId = [rs intForColumn:@"id"];
      NSString *name = [rs stringForColumn:@"name"];
      int age = [rs intForColumn:@"age"];
      NSLog(@"User ID: %d, Name: %@, Age: %d", userId, name, age);
    }
    [rs close]; // Always close the result set
    [db close];
  }
  return 0;
}

Updating and Deleting Data

Modifying or removing records also uses executeUpdate:. Just provide the appropriate SQL UPDATE or DELETE statements, again using ? for parameters.

This example updates 'Charlie's age and then deletes 'Bob':

#import <Foundation/Foundation.h>
#import "FMDB.h"

int main(int argc, const char * argv[]) {
  @autoreleasepool {
    NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *dbPath = [docsPath stringByAppendingPathComponent:@"myApp.sqlite"];
    FMDatabase *db = [FMDatabase databaseWithPath:dbPath];

    if (![db open]) { NSLog(@"Error opening db."); return 1; }
    [db executeUpdate:@"CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)"];
    [db executeUpdate:@"INSERT INTO users (name, age) VALUES (?, ?)", @"Charlie", @28];
    [db executeUpdate:@"INSERT INTO users (name, age) VALUES (?, ?)", @"Bob", @30];

    // Update Charlie's age
    BOOL updateSuccess = [db executeUpdate:@"UPDATE users SET age = ? WHERE name = ?", @29, @"Charlie"];
    if (updateSuccess) { NSLog(@"Charlie's age updated."); }

    // Delete Bob
    BOOL deleteSuccess = [db executeUpdate:@"DELETE FROM users WHERE name = ?", @"Bob"];
    if (deleteSuccess) { NSLog(@"Bob deleted."); }

    [db close];
  }
  return 0;
}

Using Transactions for Reliability

For sequences of database operations that must all succeed or all fail, use transactions. FMDB provides beginTransaction, commit, and rollback methods to ensure data integrity.

If any operation within the transaction fails, you can roll back to the state before the transaction began.

#import <Foundation/Foundation.h>
#import "FMDB.h"

int main(int argc, const char * argv[]) {
  @autoreleasepool {
    NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *dbPath = [docsPath stringByAppendingPathComponent:@"myApp.sqlite"];
    FMDatabase *db = [FMDatabase databaseWithPath:dbPath];

    if (![db open]) { NSLog(@"Error opening db."); return 1; }
    [db executeUpdate:@"CREATE TABLE IF NOT EXISTS products (id INTEGER PRIMARY KEY, name TEXT, price REAL)"];

    [db beginTransaction];
    BOOL success = YES;
    if (![db executeUpdate:@"INSERT INTO products (name, price) VALUES (?, ?)", @"Apple", @1.0]) {
        success = NO;
    }
    // Simulate a failure by trying to insert a bad value (e.g., duplicate PK if not autoinc)
    // For this example, let's just make the second insert conditional
    if (success && ![db executeUpdate:@"INSERT INTO products (name, price) VALUES (?, ?)", @"Orange", @1.5]) {
        success = NO;
    }

    if (success) {
        [db commit];
        NSLog(@"Transaction committed: products inserted.");
    } else {
        [db rollback];
        NSLog(@"Transaction rolled back due to error: %@", [db lastErrorMessage]);
    }
    [db close];
  }
  return 0;
}

Check Your Understanding

Which of the following statements about using FMDB for SQLite in Objective-C are true?

Recap: SQLite & FMDB

Great job! You've learned how to integrate SQLite databases into your Objective-C apps using the FMDB wrapper.

  • SQLite is a lightweight, embedded database.
  • FMDB simplifies SQLite operations with an Objective-C API.
  • You can open databases, create tables, and perform CRUD (Create, Read, Update, Delete) operations.
  • Always use parameterized queries for safety and consider transactions for reliability.

This knowledge is crucial for managing local data storage in your legacy Objective-C applications!

자주 묻는 질문

“FMDB를 활용한 SQLite 통합” 강의는 무료인가요?

네 — “FMDB를 활용한 SQLite 통합” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Objective-C iOS Development for Legacy & Enterprise Apps 강의 전체를 잠금 해제할 수 있습니다. Objective-C iOS Development for Legacy & Enterprise Apps 강의에는 총 4개의 강의가 포함되어 있습니다.

“FMDB를 활용한 SQLite 통합”에서 뭘 배우나요?

널리 사용되는 FMDB 래퍼를 통해 Objective-C 앱에 SQLite 데이터베이스를 통합하고 데이터를 직접 조작합니다. 브라우저에서 직접 실행하는 실습 코드로 Objective-C iOS Development for Legacy & Enterprise Apps을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Objective-C iOS Development for Legacy & Enterprise Apps을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Objective-C iOS Development for Legacy & Enterprise Apps은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“FMDB를 활용한 SQLite 통합” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Objective-C iOS Development for Legacy & Enterprise Apps 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Objective-C iOS Development for Legacy & Enterprise Apps 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 속성 목록과 보관
  2. Core Data 기초
  3. FMDB를 활용한 SQLite 통합
  4. NSUserDefaults로 환경 설정 저장하기
← Objective-C iOS Development for Legacy & Enterprise Apps(으)로 돌아가기