使用 FMDB 集成 SQLite
使用广受欢迎的 FMDB 封装库,将 SQLite 数据库集成到 Objective-C 应用中,直接操作数据。
使用 FMDB 集成 SQLite 是 CoddyKit 上的免费 Objective-C iOS Development for Legacy & Enterprise Apps 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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
FMDatabaseQueuefor 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」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Objective-C iOS Development for Legacy & Enterprise Apps 课程的其余内容,请升级到 CoddyKit PRO。 Objective-C iOS Development for Legacy & Enterprise Apps 课程共包含 4 节课。
「使用 FMDB 集成 SQLite」这节课中我会学到什么?
使用广受欢迎的 FMDB 封装库,将 SQLite 数据库集成到 Objective-C 应用中,直接操作数据。 你通过在浏览器中直接运行的动手代码来练习 Objective-C iOS Development for Legacy & Enterprise Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Objective-C iOS Development for Legacy & Enterprise Apps 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Objective-C iOS Development for Legacy & Enterprise Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「使用 FMDB 集成 SQLite」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Objective-C iOS Development for Legacy & Enterprise Apps 课中编写并运行代码吗?
能。每节 Objective-C iOS Development for Legacy & Enterprise Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 属性列表与归档
- Core Data 基础
- 使用 FMDB 集成 SQLite
- 使用 NSUserDefaults 存储偏好设置