[IOS] Database Third party framework Fmdb detailed explanation

Source: Internet
Author: User
Tags sql using sqlite manager

[IOS] Database third-party framework Fmdb A detailed explanation of the initial knowledge Fmdb

iOS native SQLite API in the data storage, need to use the C language functions, the operation is more troublesome. As a result, a series of libraries that encapsulate the SQLite API, such as,,, and so on, appear FMDB PlausibleDatabase sqlitepersistentobjects .

The Fmdb is a simple, easy-to-use package library. Therefore, it is recommended to use the third-party framework Fmdb, which is the encapsulation of the LIBSQLITE3 framework, the use of steps similar to SQLite, and its multi-threaded concurrency is handled, so it is thread-safe.

FMDB PK Sqlite
    • Advantages:
      • It is thread-safe to handle the concurrent operation of multithreading;
      • The C language API, which is encapsulated in OC SQLite , is more convenient to use.
      • Fmdb is a lightweight framework that is flexible to use.
    • Disadvantages:
      • Because it is in the language of OC and can only be used when iOS is developed, there are limitations when implementing cross-platform operations.
Important framework classes in the FMDB framework
    • FMDatabase
      • FMDatabaseobject represents a separate database for SQLite executing SQL statements
    • FMResultSet
      • Use FMDatabase result sets after executing a query
    • FMDatabaseQueue
      • Used to execute multiple queries or updates in multiple threads, which is thread-safe
Fmdb Use steps
    • Download Fmdb file github and add the Fmdb folder to your project (you can also use Cocoapods import)
    • Import libsqlite3.0 frame, import header fileFMDatabase.h
    • Code implementation, similar to SQLite using steps, create a database path, get the database path, open the database, and then the database to add, delete, change, check operation, and finally close the database.

Step.png Database Creation

When you create a Fmdatabase object, the parameter is the SQLite database file path, which can be one of the following three ways

    • The file path. The file path does not need to be real and will be created automatically if it does not exist
    • An empty string (@ ""). Indicates that an empty database is created in the Temp directory and the file is deleted when the Fmdatabase connection is closed
    • Null. An intrinsic database will be created, and the data will be destroyed when the Fmdatabase connection is closed.

    • The test model class used in this article. h


Student.png Database Usage FMDBFramework code manipulation
  • Using FMDataBase classes to build a database

      1. Get the path to the database fileNSString *doc =[Nssearchpathfordirectoriesindomains (NSDocumentDirectory,nsuserdomainmask, yes) Lastobject]; nsstring *filename = [Doc stringbyappendingpathcomponent:@ "Student.sqlite"]; //2. Get the database fmdatabase *db = [Fmdatabase databasewithpath:filename]; //3. Use the following statement, if open fails, may be insufficient permissions or insufficient resources. Usually after you open the operation, you need to call the Close method to close the database. The database must be open before interacting with the database. Failure to open or create a database can cause open failures if resources or permissions are insufficient. if ([db Open]) {//4. Genesis BOOL result = [db executeupdate:@ "CREATE TABLE IF not EXISTS t_student (id integer PRIMARY KEY autoi Ncrem ENT, Name text not null, age integer Not null); if (Result) {nslog (@ "CREATE TABLE succeeded")}}     
  • View SQL tables
    • Search for. sqlite files in the Finder based on path filename and copy to desktop
    • Open the. sqlite file using the SQLite manager under Firefox tools

      2.png
    • Data table structure

Sql.png use FMDataBaseClass Execution Database command SQL

All commands that are not select commands are treated as updates. This includes creat,update,insert,alter,begin,commit,detach,delete,drop,end,explain,vacuum,replace and so on.

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 an error. You can call the-lasterrormessage and-lasterrorcode methods to get more information.

  • Using the FMDataBase class execution database insert Command sqlinsert into

    int age = 42; 1.executeUpdate: Unsure of the parameters to use? To occupy (the next argument must be an OC object; Represents the end of the statement) [Self.db executeupdate:@]insert INTO t_student (name, age) values (?,?); ', name,@ (age)]; 2.executeUpdateWithForamat: Indeterminate parameters are occupied with%@,%d (parameter is raw data type, execution statement is case insensitive) [self.db executeupdatewithforamat:@] insert into t_student (name,age) values (%@,%i);", Name,age];//3. Parameters are how arrays are used [self.db executeupdate:@ "insert into t_student (name,age) VALUES (?,?);" withargumentsinarray:@[name,@ (age)]];            
  • Using the Fmdatabase class to perform a database delete command SQL delete

    //1. Indeterminate parameters?    To occupy (the next parameter must be an OC object, which needs to be wrapped int as an OC object) int idnum = 101; [Self.db executeupdate:@ "delete from t_student where id =?; ", @ ( Idnum)]; 2. Indeterminate parameters with%@,%d, etc. to occupy the position [self.db executeupdatewithformat:@ " Delete from t_student where name = %@, "@" Apple_name "];            
  • Using the FMDataBase class to perform database modification Command sqlupdate

      //修改学生的名字  [self.db executeUpdate:@“update t_student set name = ? where name = ?”,newName,oldName];
  • To FMDataBase execute a database query command SQL using a classselect ... from

    • The Select command is the query, and the method to execute the query begins with-excutequery.
    • When the query is executed, the error returns nil if the Fmresultset object is successfully returned. Equivalent to performing an update, supports the use of the Nserror parameter.
    • You can also use-lasterrorcode and-lasterrormessage to learn about error messages.
  • fmresultset How to get different data formats

    • intforcolumn:
    • longforcolumn:
    • longlongint Forcolumn:
    • boolforcolumn:
    • doubleforcolumn:
    • stringforcolumn:
    • dataforcolumn:
    • datanocopyforcolumn:
    • utf8stringforcolumnindex:
    • objectforcolumn:
  • Use fmresultset to get the result of the query statement

     //query entire table fmresultset *resultset = [self.db Execute query:@ "SELECT * from T_student;"]; //based on condition query Fmresultset *resultset = [self .db executequery:@ "select * from t_student where id<?;" @ (14)]; //traversal result set while ([ResultSet next]) { int idnum = [ResultSet intforcolumn:@ "id"]; nsstring *name = [resultSet objectforcolumn:@" name "]; int age = [ResultSet intforcolumn:@ ' age '];}        
  • Using the FMDataBase class to execute the database destruction command sqldrop ...

      //如果表格存在 则销毁  [self.db executeUpadate:@“drop table if exists t_student;”];
  • Using FMDatabaseQueue classes for multithreaded operations

    It is unwise to use one Fmdatabase instance in multiple threads at the same time. Now you can create a Fmdatabase object for each thread, and don't let multiple threads share the same instance, and he can't work with colleagues in multiple threads. Otherwise the program crashes or reports an exception from time to time. Therefore, do not initialize the Fmdatabase object and then use it in multiple threads. At this point, we need to use Fmdatabasequeue to create a queue execution transaction.

     1. Create queue Fmdatabasequeue *queue = [Fmdatabasequeue Databasequeuewithpath:apath]; __blockBOOL whoopssomethingwronghappened =True2. Wrap the task in a transaction [queue intransaction:^ (Fmdatabase *db,bool *rollback) {whoopssomethingwronghappened &= [db executeupdate:@ "Insert into MyTable VALUES (?)", [nsnumber numberwith:1]];whoopssomethingwronghappened &= [dbexecuteupdata:@ "Insert into MyTable VALUES (?)", [ NSNumber numberwithint:2]];whoopssomethingwronghappened &= [db executeUpdata:@] I< Span class= "hljs-built_in" >nsert into MyTable VALUES (?) " [nsnumber numberwithint:3]]; //if there is an error return if (!whoopssomethingwronghappened) {*rollback = Span class= "Hljs-literal" >yes; return;}];            

    OK, so far, I believe you have been able to use Fmdb for data persistence, its good and bad only in the continuous use of the process can be found to understand. Therefore, I hope that we have learned to write more practice and more use. In addition, we sincerely hope that we will make more valuable comments or communicate some good ideas. ^^



Wen/Chen Xiangyang (Jane book author)
Original link: http://www.jianshu.com/p/e2dbd69b6db2
Copyright belongs to the author, please contact the author to obtain authorization, and Mark "book author".

[IOS] Database Third party framework Fmdb detailed explanation

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.