1 "Open the database and create a table:
//get the path to the database fileNSString *doc =[Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES) lastobject]; NSString*filename = [Doc stringbyappendingpathcomponent:@"Students.sqlite"]; //Convert OC String to C language string Const Char*cfilename =filename. utf8string; //1. Open the database (if the database file does not exist, the Sqlite3_open function automatically creates the database file) intresult = Sqlite3_open (cFileName, &_db); if(Result = = SQLITE_OK) {//Open SuccessNSLog (@"successfully opened database"); //2. Create a watch Const Char*sql ="CREATE TABLE IF not EXISTS t_student (ID integer PRIMARY KEY autoincrement, name text NOT NULL, age integer NOT NULL); "; Char*erromsg =NULL; Result= Sqlite3_exec (self.db, SQL, NULL, NULL, &erromsg); if(Result = =SQLITE_OK) {NSLog (@"successful creation of a table"); } Else {//printf ("Genesis failure--%s--%s-%d", Erromsg, __file__, __line__);NSLog (@"Create a table failure--%s--%@-%d", erromsg, [NSString stringwithutf8string:__file__], __line__); } } Else{NSLog (@"failed to open database"); }
2 "Operation database
<1> Inserting data:
for(inti =0; i< -; i++) { //1. Splicing SQL statementsNSString *name = [NSString stringWithFormat:@"jack-%d", Arc4random_uniform ( -)]; intAge = Arc4random_uniform ( -) + -; NSString*sql = [NSString stringWithFormat:@"INSERT into T_student (name, age) VALUES ('%@ ',%d);", name, age]; //2. Execute SQL statements Char*erromsg =NULL; Sqlite3_exec (self.db, SQL. Utf8string, NULL, NULL,&erromsg); if(erromsg) {NSLog (@"failed to insert data--%s", erromsg); } Else{NSLog (@"successfully inserting data"); } }
<2> query data
Const Char*sql ="SELECT ID, name, age from T_student WHERE age <=;"; //Preparation before querying//-1 means the system automatically calculates the length of the SQL statement//sqlite3_stmt: Used to fetch dataSqlite3_stmt *stmt =NULL; if(SQLITE3_PREPARE_V2 (self.db, SQL,-1, &stmt, NULL) = = SQLITE_OK) {//no problem with SQL statementsNSLog (@"no problem with query statements"); //each time the Sqlite3_step function is adjusted, stmt points to the next record while(Sqlite3_step (stmt) = = Sqlite_row) {//Find a record//Remove Data//Remove the value of the No. 0 column field (the value of type int) intID = Sqlite3_column_int (stmt,0); //Remove the value of the 1th column field (the value of Tex type) ConstUnsignedChar*name = Sqlite3_column_text (stmt,1); //Remove the value of the 2nd column field (the value of type int) intAge = Sqlite3_column_int (stmt,2); NSLog (@"%d%s%d", ID, name, age); } } Else{NSLog (@"problem with query statement"); }