Sqlite and iossqlite for Ios development
Sqlite is an important means of ios data storage. Today, let's take a look at how to use sqlite to store data in the sandbox.
Step 1: import a framework libsqlite3.0.dylib
Select TARGETS and click '+' in the Linked Frameworks and Libraries options of General to add
Step 2: Code
1. Find the path in the sandbox
NSArray *path =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);NSString *documentPath = [path objectAtIndex:0]; NSString *dbPath = [documentPath stringByAppendingPathComponent:@"sqlite.db"];
2. Create an sqlite object and perform the open operation.
Sqlite3 * db; // open the database int res = sqlite3_open (dbPath. UTF8String, & db );
3. Create a table
NSString *sql = @"create table if not exists 'student' ('id' integer primary key autoincrement,'studentname' varchar)";int sqlRes = sqlite3_exec(db, sql.UTF8String, NULL, NULL, NULL); if (sqlRes == SQLITE_OK) { NSLog(@"create table ok"); }
4. insert data into the table
// Add NSString * sql1 = @ "insert into student (studentname) values ('small account')"; int sql1Res = sqlite3_exec (db, sql1.UTF8String, NULL ); if (sql1Res = SQLITE_ OK) {NSLog (@ "insert OK ");}
5. delete data from the table
NSString *deletesql = @"delete from student where id = 3";int deleres = sqlite3_exec(db, deletesql.UTF8String, NULL, NULL, NULL);if (deleres == SQLITE_OK) { NSLog(@"delete is ok");}
6. Modify Table Data
// Modify NSString * updateSql = @ "update student set studentname = 'hangling' where id = 4"; int updateres = sqlite3_exec (db, updateSql. UTF8String, NULL); if (updateres = SQLITE_ OK) {NSLog (@ "update is OK ");}
7. query data
Query data and, add, delete, and modify are different. We need to first create a sqlite_stmt object to store the queried data stream (Binary), and then use the sqlite3_prepare_v2 function to prepare, use sqlite3_bind _ to add a query parameter to obtain data, and disable the sqlite_stmt object.
// Query sqlite3_stmt * stmt; NSString * selectSql = @ "select * from student where id =? "; If (sqlite3_prepare_v2 (db, selectSql. UTF8String,-1, & stmt, nil) = SQLITE_ OK) {sqlite3_bind_int (stmt, 1, 4); while (sqlite3_step (stmt) = SQLITE_ROW) {int identity = sqlite3_column_int (stmt, 0); NSLog (@ "% d", identity); char * name = (char *) sqlite3_column_text (stmt, 1 ); NSLog (@ "% @", [NSString stringwithuf8string: name]);} if (stmt) {sqlite3_finalize (stmt );}
8. Disable the sqlite object of the database.
if (db) { sqlite3_close(db); }
Author: Jerry Education
Source: http://www.cnblogs.com/jerehedu/
Copyright Disclaimer: The copyright of this article is shared by Yantai jereh Education Technology Co., Ltd. and the blog Park. You are welcome to repost it. However, you must keep this statement without the consent of the author and provide the original article connection clearly on the article page, otherwise, you are entitled to pursue legal liability.
Technical Consultation: