FMDB是一个XCODE的中一个轻量级的数据库,用于将网络资源存储在本地。所以,FMDB是一个很实用,很关键的知识点。在这里写了个简单的例子,基于FMDB的添删改查操作,代码可能比较乱,希望不要伤了各位的眼睛。其中添加删除更改的操作都非常简单,不需要做太多操作,只需要用到FMDB封装好的executeUpdate方法就行了。
第一步、加入sqlite3的包文件
如图所示,依次选择并查找工程名->build phases->link binary with libraries按下方的加号键,在弹出的搜索框中搜索sqlite3,选择libsqlite3.dylib->add。至此,已经添加完毕。然后在pod 中导入FMDB这个包。
第二步、增、删、改、查 的实现
#pragma mark - FMDB数据库操作
//插入
-(
void
)insert
{
if
([_db open]) {
NSString *sql1 = [NSString stringWithFormat:
@
"INSERT INTO '%@' ('%@', '%@', '%@', '%@', '%@', '%@', '%@', '%@', '%@', '%@') VALUES ('%@', '%@', '%@', '%@', '%@', '%@', '%@', '%@', '%@', '%@')"
,
TABLENAME, @
"starting"
, @
"destination"
, @
"goodsName"
, @
"car"
, @
"goodsWeight"
, @
"goodsVolume"
,@
"intentionPrice"
,@
"bail"
,@
"mark"
,@
"status"
,_startingLabel.text,_destinationLabel.text,goodsNameTextField.text,selectVehicleLabel.text,goodsWeightTextField.text,goodsVolumeTextField.text,intentionPriceTextField.text,bailTextField.text,markLabel.text,@
"0"
];
BOOL
res = [_db executeUpdate:sql1];
if
(!res) {
NSLog(@
"error when insert db table"
);
}
else
{
NSLog(@
"success to insert db table"
);
}
[_db close];
}
}
//修改
-(
void
)update
{
if
([_db open]) {
NSString *updateSql = [NSString stringWithFormat:@
"update %@ set %@='%@' where %@='%@'"
,TABLENAME,DESTINATION,@
"目的地 上海"
,STARTING,@
"芜湖 出发地"
];
BOOL
res = [_db executeUpdate:updateSql];
if
(!res) {
NSLog(@
"error when insert db table"
);
}
else
{
NSLog(@
"success to insert db table"
);
}
[_db close];
}
}
//删除
-(
void
)
delete
{
if
([_db open]) {
NSString *deleteSql = [NSString stringWithFormat:
@
"delete from %@ where %@ = '%@'"
,
TABLENAME, STARTING, @
"芜湖 出发地"
];
BOOL
res = [_db executeUpdate:deleteSql];
if
(!res) {
NSLog(@
"error when insert db table"
);
}
else
{
NSLog(@
"success to insert db table"
);
}
[_db close];
}
}
//查询
- (
void
)query
{
if
([_db open]) {
NSString * sql = [NSString stringWithFormat:
@
"SELECT * FROM %@"
,TABLENAME];
FMResultSet * rs = [_db executeQuery:sql];
while
([rs next]) {
int
Id = [rs intForColumn:@
"ID"
];
NSString * name = [rs stringForColumn:STARTING];
NSString * age = [rs stringForColumn:DESTINATION];
NSString * address = [rs stringForColumn:GOODSNAME];
NSLog(@
"id = %d, name = %@, age = %@ address = %@"
, Id, name, age, address);
}
[_db close];
}
}
本文转载地址:http://blog.it985.com/13588.html