Data sqlite for IOS development, sqlite for ios development
Introduce the Toolkit libsqlite3.dylib, which is the C language toolkit.
Ii. Code operation Database |
1. Create and connect to the database
-(Void) _ connectDB {// 1> obtain the sandbox path as the initialization path during database creation NSString * path = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) [0]; path = [path stringByAppendingPathComponent: @ "new. sqlite "]; NSLog (@" % @ ", path); // 2> if yes, open the current link. if no, create if (SQLITE_ OK = sqlite3_open (path. UTF8String, & sqlite) {NSLog (@ "database created successfully! ");} Else {NSLog (@" database creation failed! ");}}
2. operate databases
/*** Create table */-(void) _ createTable {NSString * create = @ "create table if not exists t_Person (id integer primary key autoincrement, name text, age integer, tel text) "; [self _ execSql: create andTip: @" create TABLE operation "];} /*** insert data operation ** @ param name * @ param age * @ param tel */-(void) _ insertName :( NSString *) name andAge :( int) age andTel :( NSString *) tel {NSString * insert = [NSString stringWithFormat: @ "in Sert into t_Person (name, age, tel) values ('% @', % d, '% @') ", name, age, tel]; [self _ execSql: insert andTip: @ "insert operation"];} /***** execute Database Operations ** @ param SQL the SQL to be executed * @ param tip the operation title to be executed */-(void) _ execSql :( NSString *) SQL andTip :( NSString *) tip {char * result; if (SQLITE_ OK = sqlite3_exec (sqlite, SQL. UTF8String, NULL, NULL, & result) {NSLog (@ "% @ success! ", Tip);} else {NSLog (@" % @ failed! ", Tip );}}
3. query Databases
/*** Read data */-(void) _ readData {// 1> define the SQL statement NSString * SQL = @ "select id, name, age, tel from t_person "; sqlite3_stmt * stmt = NULL; // 2> check the correctness of the syntax if (SQLITE_ OK = sqlite3_prepare_v2 (sqlite, SQL. UTF8String,-1, & stmt, NULL) {// 3> loop result set fetch data while (sqlite3_step (stmt) = SQLITE_ROW) {// 4> note: the retrieved data can be encapsulated into the set with the standby int ID = sqlite3_column_int (stmt, 0); const unsigned char * name = sqlite3_column_text (stmt, 1); int age = sqlite3_column_int (stmt, 2); const unsigned char * tel = sqlite3_column_text (stmt, 3); NSString * names = [NSString stringwithuf8string :( const char *) name]; NSString * tels = [NSString stringwithuf8string :( const char *) tel]; NSLog (@ "% d, % @, % d, % @", ID, names, age, tels );}}}