-(void) viewdidload {[Super viewdidload]; CREATE TABLE [self creattable]; Insert data [self inserttable];} -----------------------Create a table---------------------(void) creattable{//1. Create a Database object sqlite3 *sqlite3 = nil; 2. The path of the database nsstring *path = [Nshomedirectory () stringbyappendingpathcomponent:@ "documents/mysqlite.db"]; 3. Open the database (open the database file by specifying the path, if it is not created) int result = Sqlite3_open ([path utf8string], &sqlite3); if (Result! = SQLITE_OK) {NSLog (@ "Database open failed! "); Return }//4. Create SQL statement NSString *sql = @ "Create TABLE Students (ID integer PRIMARY key,name text)"; 5. Execute SQL statement char *error = NULL; result = Sqlite3_exec (sqlite3, [SQL Utf8string], NULL, NULL, &ERROR); if (Result! = SQLITE_OK) {NSLog (@ "Execute SQL statement failed! "); 6. Close the database Sqlite3_close (sqlite3); Return }//6. Close Database Sqlite3_close (sqlite3);} -------------------------inserting Data-------------------------(void) inserttable{//1. Create a Database object Sqlite3 *sqlite3= nil; 2. The path of the database nsstring *path = [Nshomedirectory () stringbyappendingpathcomponent:@ "documents/mysqlite.db"]; 3. Open the database (open the database file by specifying the path, if it is not created) int result = Sqlite3_open ([path utf8string], &sqlite3); if (Result! = SQLITE_OK) {NSLog (@ "Database open failed! "); Return }//4. Create SQL statement//INSERT INTO students (Id,name) VALUES (' 123456 ', ' Reese ') NSString *sql = @ "INSERT INTO students (id,n AME) VALUES (?,?) "; 5. Compile the SQL statement//Create a data handle object sqlite3_stmt *stmt = nil; result = SQLITE3_PREPARE_V2 (sqlite3, [SQL Utf8string], 1, &stmt, nil); if (Result! = SQLITE_OK) {NSLog (@ "compile failed"); Close Database Sqlite3_close (sqlite3); Return }//6. Bind data to the data handle inside Sqlite3_bind_int (stmt, 1, 123457); Sqlite3_bind_text (stmt, 2, "Zhang San",-1, nil); 7. Operation of the data handle result = Sqlite3_step (stmt); if (result = = Sqlite_error | | result = = sqlite_misuse) {NSLog (@ "Insert failed"); Close data handle sqlite3_finalize (stmt); Close the database Sqlite3_close (sqlite3); return; }//8. Successful execution NSLog (@ "Insert success"); Close data handle sqlite3_finalize (stmt); Close Database Sqlite3_close (sqlite3); }
SQLite creates tables and adds data