In iOS development, if you use the SQLite library to write the database will be more troublesome, Fmdb is the package of SQLite, there are more friendly concise statement.
1,fmdb:fmdb
2, import the file under SRC, when used #import "FMDatabase.h"
3, create a database
#define KDOCDIR [Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES) ObjectAtIndex: 0]
#define DbPath [Kdocdir stringbyappendingpathcomponent:@"test.db"]
Fmdatabase *db = [fmdatabase databasewithpath:dbPath];
if (! [DB open]) {
NSLog(@ "Could not open db.") );
[DB close];
}
4, CREATE TABLE table1, three field IDs are shaped, name is a string, image is binary.
NSString *sqlstr =@ "CREATE TABLE table1 (id integer, name text, image blob)";
BOOL res = [db executeupdate: sqlstr];
if (!res) {
NSLog(@ "error when creating DB tabletable1");
[DB close];
}
5, inserting data
int idvalue;
nsstring *name;
NSData *data;
sqlstr = @ "INSERT into table1 values (?,?,?)" ;
res = [db executeupdate: sqlstr,idvalue,name,data];
if (!res) {
NSLog(@ "error when insert intotable1");
[DB close];
}
INSERT statement Please do not write this:
sqlstr = [nsstring stringwithformat:@ "INSERT INTO table1 values ('%@ ', '%@ ', '%@ ') ",idvalue, name, data];
res = [db executeupdate: sqlstr];
if (!res) {
NSLog(@ "error when insert intotable1");
[DB close];
}
In this case, the binary data will not be saved to the table.
6. Querying data
Fmresultset *s = [db executeQuery:@ "SELECT * FROM table1"];
while ([s next]) {
int idvalue =[s intforcolumn:@ "id"];
NSString *name =[s stringforcolumn:@ "name"];
NSData *data =[s dataforcolumn:@ "image"];
}
IOS FMDB Use