IOS FMDB Use

Source: Internet
Author: User

In iOS development, if you use the SQLite library to write the database will be more troublesome, Fmdb is the package of SQLite, there are more friendly concise statement.


1,fmdb:fmdb


2, import the file under SRC, when used #import "FMDatabase.h"



3, create a database

#define KDOCDIR [Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES) ObjectAtIndex: 0]

#define DbPath [Kdocdir stringbyappendingpathcomponent:@"test.db"]

Fmdatabase *db = [fmdatabase databasewithpath:dbPath];

if (! [DB open]) {

NSLog(@ "Could not open db.") );

[DB close];

}


4, CREATE TABLE table1, three field IDs are shaped, name is a string, image is binary.

NSString *sqlstr =@ "CREATE TABLE table1 (id integer, name text, image blob)";

BOOL res = [db executeupdate: sqlstr];

if (!res) {

NSLog(@ "error when creating DB tabletable1");

[DB close];

}


5, inserting data

int idvalue;

nsstring *name;

NSData *data;


sqlstr = @ "INSERT into table1 values (?,?,?)" ;

res = [db executeupdate: sqlstr,idvalue,name,data];

if (!res) {

NSLog(@ "error when insert intotable1");

[DB close];

}


INSERT statement Please do not write this:

sqlstr = [nsstring stringwithformat:@ "INSERT INTO table1 values ('%@ ', '%@ ', '%@ ') ",idvalue, name, data];

res = [db executeupdate: sqlstr];

if (!res) {

NSLog(@ "error when insert intotable1");

[DB close];

}

In this case, the binary data will not be saved to the table.


6. Querying data

Fmresultset *s = [db executeQuery:@ "SELECT * FROM table1"];

while ([s next]) {

int idvalue =[s intforcolumn:@ "id"];

NSString *name =[s stringforcolumn:@ "name"];

NSData *data =[s dataforcolumn:@ "image"];

}







IOS FMDB Use

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.