IOS Fmdb Try it a little bit.

Source: Internet
Author: User

Today from 9 in the morning, has been watching fmdb, know 11:40 noon. My efficiency is not very low. In the middle also encountered a few small bugs.

  

Although did a small demo, but I think it is not comparable in the use of the project in the exercise of many, first a summary.

    1. Download the Fmdb file first;
    2. introduced into the project;
    3. Add <libsqlite3.dylib> Library;
    4. Create a new project and start using

Let's say it in one of the following strips:

    1. Fmdb: Https://github.com/ccgus/fmdb;
    2. Fmdb inside the ' Fmdb ', introduced into the project, others can not;
    3. In link Binary with Libraries, the introduction of Libsqlite3.dylib;
    4. Inside the Viewcontroller, introduce the header file
#import <sqlite3.h> #import "FMDB.h"

  

Preparations have been completed, we formally began to write code, first of all, we have to understand is: FMDB, is the package SQLite, SQLite is written in C, we have to use the C language. Since it is sqlite, that will naturally involve adding and removing changes, we will carefully talk about these features.

1. Before we proceed with the increase and deletion, we need to establish a database so that we can operate:

    Get document Path    NSString * documentpath = [Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES) objectatindex:0];    NSString * DbPath = [documentpath stringbyappendingpathcomponent:@ "database.db"];    NSLog (@ "DbPath =%@", dbPath);    Create    a database/**     1, Fmdb creates one yourself when the database file does not exist.     2, if you pass in a parameter is empty string: @ "", then Fmdb will create the database in the temporary file directory, the database is disconnected, the database file is deleted.     3. If you pass in a parameter that is NULL, it will establish a database in memory and the database file is deleted when the database is disconnected.     */    Fmdatabase * db = [fmdatabase Databasewithpath:dbpath];

The database file is then created, and it can be opened and normally opened:

if (![ DB Open]) {        NSLog (@ "Could not open db,lasterrormessage  =%@", db.lasterrormessage);        return;    } else{        NSLog (@ "open success");    }

2. After the database is set up, we will build a table to classify the properties

    CREATE TABLE    if ([db Open]) {        NSString * sqlcreatetable = [nsstring stringwithformat:@ "CREATE table if not EXISTS Per Sonlist (Name text PRIMARY KEY autoincrement, age integer, Sex integer, Phone text, Address text, Photo blob) "];                Write Database        BOOL res = [db executeupdate:sqlcreatetable];        if (!res) {            NSLog (@ "error when creating the table");        } else{            NSLog (@ "Success");        }        [DB close];    } else{        NSLog (@ "table is not open, or tableview already exists");    }

3. Insert Data

    /**     *  -Insert data     Insert data in front of the same, with executeupdate after adding syntax on it. The difference is that because the inserted data is related to the OBJECTIVE-C variable, using the # number in the string represents these variables.     */    if ([db Open]) {        if ([db executeupdate:@ "INSERT into '%@ ' ('%@ ', '%@ ', '%@ ', '%@ ', '%@ ', '%@ ') VALUES (?,?,?, ?,?,?) ", tablename,name,age,sex,phone,address,photo,@" Tang ", 22,1,@" 18510860420 ", @" Ruida ", @" "]) {            NSLog @" Success ");        } else{            NSLog (@ "failed");        }        [DB close];    }

4. Update information

All commands that are not select commands are treated as updates. This includes CREATE, UPDATE, Insert,alter,commit, BEGIN, DETACH, DELETE, DROP, END, EXPLAIN, VACUUM, and REPLACE (etc.). Simply put, a command that does not start with a select is an update command. Performs an update that returns a bool value. Yes indicates successful execution, otherwise it indicates that there are errors. You can call the-lasterrormessage and-lasterrorcode methods to get more information.
    if ([db Open]) {        NSString * updatesql= [nsstring stringwithformat:@ "UPDATE '%@ ' SET '%@ ' = '%d ' WHERE '%@ ' = '%d '", tab LENAME,AGE,15,AGE,22];        if ([db Executeupdate:updatesql]) {            NSLog (@ "update succeeded");        } else{            NSLog (@ "update failed");        }    }

5. Enquiry

    if ([db Open]) {        //query        nsstring * sql = [NSString stringwithformat:@ "SELECT * from%@", TABLENAME];        Fmresultset * ResultSet = [db executequery:sql];                /**         *  use [Rs next] to poll the data returned by query, each time the next can get a row corresponding to the value, and using [Rs Stringforcolumn:] or [RS Intforcolumn:] The method turns the value into the Object-c form. Use [Rs Close] to close the results when the data is exhausted.         *        /while ([ResultSet next]) {            NSString * name = [ResultSet stringforcolumn:name];            int age = [ResultSet intforcolumn:age];            NSLog (@ "name =%@--age =%d", name,age);        }    }

6. Delete

    if ([db Open]) {        //delete        NSString * deletesql = [nsstring stringwithformat:@ "Delete from%@ where%@ = '%@ '", Tablenam e,name,@ "Tang");        Fmresultset * ResultSet = [db executequery:deletesql];        if ([db Executeupdate:deletesql]) {            NSLog (@ "Deletesql succeeded");        } else{            NSLog (@ "Deletesql failed");        }                [ResultSet close];    }

7. Create a queue

If you use a multi-threaded database in your application, you need to use Fmdatabasequeue to ensure thread safety. It is not common in the application to use a Fmdatabase object in multiple threads to manipulate the database, which can cause confusion in database data. For multi-threaded operation of database security, Fmdb uses Fmdatabasequeue, using Fmdatabasequeue is very simple, first with a database file address to the initial fmdatabasequeue, and then you can be a closure (block) Passed into the Indatabase method. Operate the database in a closure without directly participating in the management of the fmdatabase.

    Create Queue    fmdatabasequeue * Databasequeue = [Fmdatabasequeue Databasequeuewithpath:dbpath];    [Databasequeue indatabase:^ (Fmdatabase *db) {//        [DB executeupdate:@ INSERT into Personlist VALUES (?) ", [NSNumber Numberwithint:2]];                Fmresultset * ResultSet = [db executequery:@ "select * from Personlist"];        while ([ResultSet next]) {            NSString * a = [ResultSet stringforcolumn:name];            NSLog (@ "a =%@", a);        }    }];

  

Fmresultset provides a number of ways to get the value of the desired format: intForColumn:longForColumn:longLongIntForColumn:boolForColumn:doubleFor Column:stringForColumn:dataForColumn:dataNoCopyForColumn:UTF8StringForColumnIndex:objectForColumn:

IOS Fmdb Try it a little bit.

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.