Using Fmdatabase to operate Sqlite3 database is very simple and convenient
1 //2 //main.m3 //Iosdemo0602_sqlite34 //5 //Created by Yao_yu on 14-6-2.6 //Copyright (c) 2014 Yao_yu. All rights reserved.7 //8 9 #import<UIKit/UIKit.h>Ten #import "FMDatabase.h" One A voidtest01 (); -BOOL Isfile (NSString *path); -BOOL Isdir (NSString *path); the - intMainintargcChar*argv[]) - { - @autoreleasepool { + test01 (); - } + return 0; A } at - voidtest01 () - { -Nsarray *paths =nssearchpathfordirectoriesindomains (Nsdocumentationdirectory, Nsuserdomainmask, YES); -NSString *docpath = [Paths Objectatindex:0]; -NSString *dbpath = [Docpath stringbyappendingpathcomponent:@"Yy/data2"]; in //NSLog (@ "%@", DBPath); - if(!Isdir (DBPath)) { toNsfilemanager *filemanager =[Nsfilemanager Defaultmanager]; + [FileManager createdirectoryatpath:dbpath withintermediatedirectories:yes attributes:nil Error:nil]; - } the *NSString *dbfile = [DBPath stringbyappendingpathcomponent:@"data.db"]; $NSLog (@"%@", dbfile);Panax Notoginseng - //Initialize theFmdatabase *db =[Fmdatabase databasewithpath:dbfile]; + //Open Database A [DB open]; the + //Delete a table -[DB executeupdate:@"drop table Persons"]; $ $ //Add Table -[DB executeupdate:@"CREATE TABLE persons (ID, name)"]; - the //Delete old data -[DB executeupdate:@"Delete from persons"];Wuyi the //using transactions to add data - [DB BeginTransaction]; Wu for(intI=0; i<10000; i++) - { About[DB executeupdate:@"INSERT into persons values (?,?)", [NSString stringWithFormat:@"%d", I], [NSString stringWithFormat:@"section%d", I]]; $ } - [DB commit]; - - //data Query AFmresultset *cursor = [db executeQuery:@"SELECT * FROM Persons"]; + intNCols =Cursor.columncount; the while([cursor next]) { - for(intI=0; i<ncols; i++) { $printf"%s", [[Cursor stringforcolumnindex:i] utf8string]); the } theprintf"\ n"); the } thecursor =Nil; - in //Close the database the [DB close]; the About //To Delete a database test file the [[Nsfilemanager Defaultmanager] Removeitematpath:dbfile Error:nil]; the the } + -BOOL Isfile (NSString *path) the {BayiNsfilemanager *filemanager =[Nsfilemanager Defaultmanager]; theBOOL Isdir =NO; the if([FileManager fileexistsatpath:path isdirectory: &Isdir]) { - returnIsdir = =NO; - } the returnNO; the } the theBOOL Isdir (NSString *path) - { theNsfilemanager *filemanager =[Nsfilemanager Defaultmanager]; theBOOL Isdir =NO; the if([FileManager fileexistsatpath:path isdirectory: &Isdir]) {94 returnIsdir = =YES; the } the returnNO; the}