"IOS" Using SQLite and Fmdb

Source: Internet
Author: User

SQLite in iOS is exactly the same as in Android, except that the calling method is different. If a single call from the Android package is better than a set of helper, and iOS native C language of several functions in operation, more trouble. However, the introduction of third-party framework Fmdb, the use of more convenient.


First, the basic use of SQLite

Steps to use:

1.Import System Framework(Clanguage). (libsqlite3)2.header File#import <sqlite3.h.3. Sqlite3_open(filename.utf8string, &_DB); Open or create a data *_dbDefine yourself aSqlite3the member variable.to be used when checking.4.sqlite3_exec(_db, SQL, NULL, null,&error);*This function can be used toInsert,Delete,UpdateOperation.5.Query OperationsSelect.*SQLITE3_PREPARE_V2(_db, SQL,-1, &stmt, NULL);prepare before you make a query,DetectionSQLstatement is correct.*sqlite3_step (stmt)extracting data from a query,extract one at a time.*Sqlite3_column_text (stmt, 0)Remove Section0columns of data.
look directly at the code to make it easier to understand:To Create or open a database:
   0. Get the file address    nsstring *path = [Nssearchpathfordirectoriesindomains (nsdocumentdirectory, Nsuserdomainmask, YES) Lastobject];    NSString *filename = [path stringbyappendingpathcomponent:@ "T_student.sqlite"];    1. Open or create a database    //(1. If the database does not exist, it will automatically create the database and open, 2. If the database store will automatically open the database)    int result = Sqlite3_open ( Filename.utf8string, &_db);    if (result = = SQLITE_OK) {        NSLog (@ "Open database succeeded");        2. CREATE TABLE        /**         sqlite3 Pass Open database         sql: Database statement to execute         */        const char *sql = "CREATE table IF not EXISTS t _student (ID integer PRIMARY KEY autoincrement, name TEXT NOT NULL, age INTEGER not null); ";        char *error = nil;        Execute SQL statement in DB database        sqlite3_exec (self.db, SQL, NULL, NULL, &ERROR);        if (error) {            NSLog (@ "Failed to create TABLE");        } else        {            NSLog (@ "CREATE table succeeded");        }    } else    {         NSLog (@ "Open database Failed");    }

Insert data: (update, delete similar)
1. Splicing Insert SQL statement        nsstring *name = [NSString stringwithformat:@ "jonathan-%d", I];        int age = Arc4random_uniform (+);        NSString *sql = [NSString stringwithformat:@ "INSERT into T_student (name, age) VALUES ('%@ ',%d);", name, age];        char *error = nil;        2. Execute the INSERT SQL statement        sqlite3_exec (self.db, SQL. Utf8string, NULL, NULL, &ERROR);        if (error) {            NSLog (@ "Add failed");        } else        {            NSLog (@ "add success");        }

Query data:
const char *sql = "SELECT Name, age from T_student;"; /    Char *error = nil;//    sqlite3_exec (self.db, SQL, NULL, NULL, &ERROR);    Sqlite3_stmt *stmt; Used to extract data    //1. Before making the query, check that the SQL statement is correct    int result = SQLITE3_PREPARE_V2 (self.db, SQL,-1, &stmt, NULL);    if (result = = SQLITE_OK) {//Ready to complete, no error        //2. Extract the data from the query to stmt, one at a time        ///If the return value is Sqlite_row, it represents the extraction to a record while       ( Sqlite3_step (stmt) = = Sqlite_row)       {           //3. Remove data from the No. 0 column in the extracted Records (data)           const unsigned char *name = Sqlite3_column _text (stmt, 0);           int age = Sqlite3_column_int (stmt, 1);           NSLog (@ "%s%d", name, age);       }    }

second, the use of Fmdbthe benefit of Fmdb is the encapsulation of the basic C library for ease of use. At the same time, it also provides the methods of the multi-threaded operation database to read dirty data and so on.
Frame Address: Https://github.com/ccgus/fmdb

Use: (Needfmdatabase *dbmember Variables)Create or Open:
0. Get the sandbox path    nsstring *path = [Nssearchpathfordirectoriesindomains (nsdocumentdirectory, Nsuserdomainmask, YES) Lastobject];    NSString *filename = [path stringbyappendingpathcomponent:@ "T_student.sqlite"];    1. Obtain the database object    self.db = [Fmdatabase databasewithpath:filename];        2. Open    the database if ([self.db Open]) {        NSLog (@ "open successfully");        2.1 CREATE TABLE       BOOL success =  [self.db executeupdate:@ "CREATE table IF not EXISTS t_student (id INTEGER PRIMARY KEY AUT Oincrement NOT NULL, name TEXT is not NULL, the age INTEGER is not null); "];        if (success) {            NSLog (@ "CREATE table succeeded");        } else        {            NSLog (@ "Failed to create TABLE");}    } else    {        NSLog (@ "Open failed");    }

Insert operation:(update, delete, similar to this)
BOOL success = [Self.db executeupdate:@ "INSERT into T_student (name, age) VALUES (?,?);", @ "Xuneng", @ (10)];//Note You can only stitch object types C0/>if (Success) {            NSLog (@ "add success");        } else        {            NSLog (@ "Add failed");        }

Inquire:
1. Query    fmresultset *set = [self.db  executequery:@ "select * from T_student;];        2. Remove the data    while ([set next]) {                //Remove name//       NSString *name = [set stringforcolumnindex:1];        Remove Age/       int. = [set intforcolumnindex:2];        NSString *name = [set stringforcolumn:@ "name"];        int age = [Set intforcolumn:@ ' age '];        NSLog (@ "name =%@, age =%d", name, age);    }

Fmdb can also define the operation queue Fmdatabasequeue, this queue is thread-safe. (Fmdatabase is not thread-safe)
It can also open thingsand submit things. Very convenient to use.
can refer to Https://github.com/ccgus/fmdb on the study, written in quite detailed.

Reprint Please specify Source: http://blog.csdn.net/xn4545945



"IOS" Using SQLite and Fmdb

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.