1. Framework-based fmdatabase.
2. Connection class
# Import <Foundation/Foundation. h>
# Import " Fmdatabase. h "
@ InterfaceDbhelper: nsobject {
Fmdatabase * dB;
}
-(Bool) initdatabase;
-(Void) Closedatabase;
-(Fmdatabase *) getdatabase;
@ End
# Import "Dbhelper. h"
# DefineDb_name @ "menu. DB"
@ ImplementationDbhelper
-(Bool) initdatabase
{
Bool success;
Nserror * error;
Nsfilemanager * fm = [nsfilemanager defamanager manager];
Nsarray * paths = nssearchpathfordirectoriesindomains (nsdocumentdirectory, nsuserdomainmask, yes );
Nsstring * documentsdirectory = [paths objectatindex: 0 ];
Nsstring * writabledbpath = [documentsdirectory stringbyappendingpathcomponent: db_name];
Success = [FM fileexistsatpath: writabledbpath];
If (! Success ){
Nsstring * defaultdbpath = [[[nsbundle mainbundle] bundlepath] stringbyappendingpathcomponent: db_name];
Nslog ( @" % @ " , Defaultdbpath );
Success = [FM copyitematpath: defaultdbpath topath: writabledbpath error: & error];
If (! Success ){
Nslog ( @" Error: % @ " , [Error localizeddescription]);
}
Success = yes;
Nslog ( @" Success to open database. " );
}
If (SUCCESS ){
DB = [[fmdatabase databasewithpath: writabledbpath] retain];
If ([DB open]) {
[DB setshouldcachestatements: Yes];
} Else {
Nslog ( @" Failed to open database. " );
Success = no;
}
}
Return Success;
}
-(Void) Closedatabase
{
[DB close];
}
-(Fmdatabase *) getdatabase
{
If([Self initdatabase]) {
ReturnDB;
}
ReturnNULL;
}
-(Void) Dealloc
{
[Self closedatabase];
[DB release];
[Super dealloc];
}
@ End
3. Call
-(Bool) updatadata :( nsarray *) List
{
Dbhelper * dbhelper = [[
Dbhelper alloc] init];
Fmdatabase * DB = [dbhelper getdatabase];
[DB begintransaction];
[DB executeupdate: @" Delete from dishtype " ];
If ([DB haderror]) {
Nslog ( @" Err % d: % @ " , [DB lasterrorcode], [dB lasterrormessage]);
[DB rocback];
}
For ( ID Model In List)
{
[Self insertwithmodel: Model DB: dB];
}
[DB commit];
[Dbhelper release];
}
-(Bool) insertwithmodel :( dishtypemodel *) model dB :( fmdatabase *) dB
{
[DBExecuteupdate: @ "insert into dishtype (ID, name, IMG, sequence) values (?,?,?,?) ",
Model. ID, model. Name, model. IMG, model. Sequence];
If ([dB haderror]) {
Nslog (@ "Err % d: % @", [dB lasterrorcode], [dB lasterrormessage]);
[DB rockback];
Return false;
}
Return true;
}