It is very convenient to store local data using Fmdb.
1. Search Fmdb on GitHub to import the compressed package into the project (if your Mac has cocoapod you can add it directly via Cocoapod)
2. The following code is a variety of operations through Fmdb multiple databases, several of which need to be noted: (1). The Ceasar in the program is the table name (2). Modify database data prepare strings in advance string values are enclosed in single quotation marks: NSString *temp = [NSString stringwithformat:@ "UPDATE%@ SET%@ = '%@ ' WHERE%@ = '%@ ' @ "Ceasar", @ "Name", @ "Hao", @ "age", [NSNumber numberwithint:100];
NSString *path = @ "/users/shijieli/desktop/test.sqlite";
Fmdatabase *db = [Fmdatabase Databasewithpath:path];
if ([db Open]) {//CREATE TABLE
BOOL res = [db executeupdate:@ "CREATE TABLE IF not EXISTS Ceasar (Name text, age integer, Photo blob)"];
if (!res) {
NSLog (@ "error when creating DB table");
} else {
NSLog (@ "Success to creating DB table");
}
[DB close];
}
if ([db Open]) {//Add data
BOOL res = [db executeupdate:@ "INSERT into Ceasar (Name, age, Photo) VALUES (?,?,?)" @ "Gaius", [NSNumber Numberwithintege R:100],[nsdata datawithcontentsoffile:@ "/users/shijieli/desktop/testpicture.jpg"];
if (res) {
NSLog (@ "Success to insert DB table");
} else {
NSLog (@ "error when insert DB table");
}
[DB close];
}
if ([db Open]) {//query
Fmresultset * rs = [db executequery:@ "select * from Ceasar"];
while ([Rs next]) {
NSString * name = [rs stringforcolumn:@ "name"];
int age = [rs intforcolumn:@ ' age '];
NSData *photo = [rs dataforcolumn:@ "photo"];
NSLog (@ "name =%@, age =%d", name, age);
BOOL iscreate = [[Nsfilemanager Defaultmanager] createfileatpath:@ "/users/shijieli/desktop/car.jpg" Contents:photo Attributes:nil];
if (!iscreate) {
NSLog (@ "****** create failure");
}
}
[DB close];
}
if ([db Open]) {//Modify data
NSString *temp = [NSString stringwithformat:@ "UPDATE%@ SET%@ = '%@ ' WHERE%@ = '%@ '", @ "Ceasar", @ "Name", @ "H AO ", @" age ", [NSNumber numberwithint:100];
BOOL res = [db executeupdate:temp];
if (!res) {
NSLog (@ "error when update db table");
} else {
NSLog (@ "Success to update DB table");
// }
//
[DB close];
//
// }
if ([db Open]) {//Clear table
BOOL res = [db executeupdate:@ "DELETE from Ceasar"];
if (!res) {
NSLog (@ "Delete failure");
// }
// }
if ([db Open]) {//delete data
NSString *deletesql = [NSString stringWithFormat:
@ "Delete from%@ where%@ = '%@ '",
@ "Ceasar", @ "Name", @ "Hao"];
BOOL res = [db executeupdate:deletesql];
if (!res) {
NSLog (@ "error when delete db table");
} else {
NSLog (@ "Success to delete db table");
}
[DB close];
}
}
IOS Tri-Party Library Fmdb usage