IOS Operations Database (FMDB)

Source: Internet
Author: User
Tags uicontrol

Recently, the company is doing offline cache of things, with the SQLite database saved. Using a third-party class library fmdatabase the database, this is a small demo I wrote, nonsense not to say, first on:


In the operation of the database encountered a small problem, SQLite string type is used in text to store, int type with integer,float with real,

It is important to note that when inserting data, if the string type is inserted directly, but if float or integer type, it is necessary to convert the insertion value into the NSNumber data type as follows: [nsnumber numberwithint:]


When debugging the database operation, it is best to do in the emulator, and then print out the database path, and then look at the data inside the database, whether it exists, here is recommended to view the SQLite database software, very small, the function is not strong but also barely enough. (No points)

http://download.csdn.net/detail/zyzxrj/8203551


It is also important to note that when the database is deleted or deleted, the database will be locked, causing the insertion or deletion to fail. However, the query operation can.

Refer to the following statement

nsstring *createmessagetable = @ "CREATE table if not EXISTS message (Messageno integer prima Ry Key,failldreason text,contract text,contractphone text,isread integer, orderstatus integer, MessageType integer, Acceptmessagetime text,appointedtime text,orderdate text,startstation text,arrivalstation text,transportLocation Text,tradeno text) ";

This interface I in order to save time directly xib dragged, I believe that there is a certain basis for the development of iOS people can be written in code, I do not nonsense, mainly say some database operation problems:

DataBaseViewController.h:

#import <UIKit/UIKit.h> @interface databaseviewcontroller:uiviewcontroller@property (weak, nonatomic) Iboutlet Uitextfield *nametextfield; @property (weak, nonatomic) Iboutlet Uitextfield *sextextfield; @property (weak, nonatomic) Iboutlet Uitextfield *agetextfield;-(ibaction) Save: (ID) sender;-(ibaction) query: (ID) sender;-(ibaction) Querybycondition: (ID) sender;-(ibaction) Update: (ID) sender;-(ibaction) Deletebycondition: (ID) sender; @end

DATABASEVIEWCONTROLLER.M:

databaseviewcontroller.m//location////Created by admin on 14-11-17.//Copyright (c) 2014 admin. All rights reserved.//#import "DataBaseViewController.h" #import "FMDatabase.h" #import "FMDatabaseQueue.h" #define Ios7_or_later ([[[Uidevice Currentdevice] systemversion]floatvalue] >= 7.0) @interface Databaseviewcontroller () @ End@implementation databaseviewcontroller-(ID) initwithnibname: (NSString *) Nibnameornil Bundle: (NSBundle *)    nibbundleornil{self = [super Initwithnibname:nibnameornil Bundle:nibbundleornil]; if (self) {//Custom initialization} return to self;}    -(void) viewdidload{[Super Viewdidload];    Controller, click on the blank place, hide the keyboard cgrect cgrect = Self.view.frame; if (!    Ios7_or_later) {CGRECT.ORIGIN.Y-= 20;    } Uicontrol *clickcontrol = [[Uicontrol alloc] init];    Clickcontrol.frame = CGRect;    [Clickcontrol addtarget:self Action: @selector (Hidekeyboard) forcontrolevents:uicontroleventtouchupinside];   [Self.view Addsubview:clickcontrol]; [Self.view Sendsubviewtoback:clickcontrol];}    -(void) didreceivememorywarning{[Super didreceivememorywarning]; Dispose of any resources the can be recreated.}    Hide Soft Keyboard-(void) hidekeyboard{[_nametextfield Resignfirstresponder];    [_agetextfield Resignfirstresponder]; [_sextextfield Resignfirstresponder];} -(Ibaction) Save: (ID) Sender {//Get the database file under the Document folder, no then create nsstring *docpath = [Nssearchpathfordirectoriesindomains (    NSDocumentDirectory, Nsuserdomainmask, YES) objectatindex:0];    NSString *dbpath = [DocPath stringbyappendingpathcomponent:@ "user.db"];    NSLog (@ "%@", DbPath);    Get the database and open fmdatabase *database = [Fmdatabase Databasewithpath:dbpath]; if (![        Database Open] {NSLog (@ "Failed to open databases");    return; }//CREATE TABLE (only update and query operations in Fmdb, out of query other update operations) [DataBase executeupdate:@ "CREATE table if not exists user (name text,    Gender text,age integer) "]; Insert data BOOL Inser = [DataBase executeupdate:@ "insert into user values (?,?,?)", _nametextfiEld.text,_sextextfield.text,_agetextfield.text]; if (inser) {Uialertview *alert = [[Uialertview alloc]initwithtitle:@ ' Prompt ' message:@ ' information saved successfully ' Delegate:self CancelBut        Tontitle:nil otherbuttontitles:@ "OK", nil];    [Alert show]; } [DataBase close];} Query All-(ibaction) query: (ID) Sender {nsstring *docpath = [Nssearchpathfordirectoriesindomains (NSDocumentDirectory,    Nsuserdomainmask, YES) objectatindex:0];        NSString *dbpath = [DocPath stringbyappendingpathcomponent:@ "user.db"];    Fmdatabase *database = [Fmdatabase Databasewithpath:dbpath]; if (![        Database Open] {NSLog (@ "Failed to open databases");    return;    } fmresultset *resultset = [DataBase executequery:@ "SELECT * from user"];        while ([ResultSet next]) {nsstring *name = [resultSet stringforcolumn:@ "name"];        NSString *genter = [ResultSet stringforcolumn:@ "gender"];        int age = [ResultSet intforcolumn:@ ' age '];    NSLog (@ "name:%@,gender:%@,age:%d", name,genter,age); } [DatabaSe close];} Conditional query-(ibaction) Querybycondition: (ID) Sender {nsstring *docpath = [Nssearchpathfordirectoriesindomains (    NSDocumentDirectory, Nsuserdomainmask, YES) objectatindex:0];    NSString *dbpath = [DocPath stringbyappendingpathcomponent:@ "user.db"];    Fmdatabase *database = [Fmdatabase Databasewithpath:dbpath]; if (![    DataBase Open] {return;    }//fmresultset *resultset = [dataBase executequery:@ "Select *from user where name =?", @ "ZY"];    Fmresultset *resultset = [DataBase executequerywithformat:@ "SELECT * from user where name =%@", @ "Zy"];        while ([ResultSet next]) {nsstring *name = [ResultSet stringforcolumnindex:0];        NSString *gender = [ResultSet stringforcolumn:@ "gender"];        int age = [ResultSet intforcolumn:@ ' age '];    NSLog (@ "name:%@,gender:%@,age:%d", name,gender,age); } [DataBase close];} -(ibaction) Update: (ID) Sender {nsstring *docpath = [Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES) obJECTATINDEX:0];    NSString *dbpath = [DocPath stringbyappendingpathcomponent:@ "user.db"];    Fmdatabase *database = [Fmdatabase Databasewithpath:dbpath]; if (![    DataBase Open] {return; }//parameter must be a subclass of NSObject, Int,double,bool this basic type, need to encapsulate the corresponding wrapper class to be BOOL update = [dataBase executeupdate:@ "Update user set AG E =?    WHERE name =? ", [NSNumber numberwithint:24],@" ZY "]; if (update) {Uialertview *alert = [[Uialertview alloc]initwithtitle:@ ' Prompt ' message:@ ' information updated successfully ' Delegate:self Cancelbu        Ttontitle:nil otherbuttontitles:@ "OK", nil];    [Alert show]; } [DataBase close];} -(Ibaction) Deletebycondition: (ID) sender{nsstring *docpath = [Nssearchpathfordirectoriesindomains (    NSDocumentDirectory, Nsuserdomainmask, YES) objectatindex:0];    NSString *dbpath = [DocPath stringbyappendingpathcomponent:@ "user.db"];    Fmdatabase *database = [Fmdatabase Databasewithpath:dbpath]; if (![    DataBase Open] {return; } BOOL Delete = [DataBase Executeupdatewithformat:@ "Delete from user where name =%@" @ "Zy"]; if (delete) {Uialertview *alert = [[Uialertview alloc]initwithtitle:@ ' Prompt ' message:@ ' message deleted successfully ' Delegate:self Cancelbu        Ttontitle:nil otherbuttontitles:@ "OK", nil];    [Alert show]; } [DataBase close];} @end
The following is the entire demo source file (no points.):

http://download.csdn.net/detail/zyzxrj/8203583

If you have any confusion, please refer to the code



IOS Operations Database (FMDB)

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.