@implementation HMShopTool
static FMDatabase *_db;
+ (void)initialize
{
// 1.打开数据库
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)lastObject]stringByAppendingPathComponent:@"shops.sqlite"];
_db = [FMDatabase databaseWithPath:path];
[_db open];
// 2.创表
[_db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_shop (id integer PRIMARY KEY, name text NOT NULL, price real);"];
}
+ (void)addShop:(HMShop *)shop
{
[_db executeUpdateWithFormat:@"INSERT INTO t_shop(name, price) VALUES (%@, %f);", shop.name, shop.price];
}
+ (NSArray *)shops
{//得到结果集
FMResultSet *set = [_db executeQuery:@"SELECT * FROM t_shop;"];
// 不断往下取数据
NSMutableArray *shops = [NSMutableArrayarray];
while (set.next) {
// 获得当前所指向的数据
HMShop *shop = [[HMShop alloc] init];
shop.name = [set stringForColumn:@"name"];
shop.price = [set doubleForColumn:@"price"];
[shops addObject:shop];
}
return shops;
}
@end
(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// - 添加数据
// for (int i = 0; i<100; i++) {
// HMShop *shop = [[HMShop alloc] init];
// shop.name = [NSString stringWithFormat:@"枕头--%d", i];
// shop.price = arc4random() % 200;
// [HMShopTool addShop:shop];
// }
// - 查询数据
NSArray *shops = [HMShopToolshops];
for (HMShop *shopin shops) {
NSLog(@"%@ %f", shop.name, shop.price);
}
// [self.db executeUpdate:@"DELETE FROM t_shop WHERE price < 800;"];
//
// [self query];
// 1.建表
/** NSString *strSql = @"Create Table if not exists FavoriteInfo(id integer primary key autoincrement, appId varchar(256), name varchar(256), appType varchar(256), iconUrl varchar(512))";
[_fmdb executeUpdate:strSql]
//创建表 这个的 Photo 是二进制类型的
//[membersDB executeUpdate:@"CREATE TABLE PersonList (Name text, Age integer, Sex integer,Phone text, Address text, Photo blob)"];
*/
// 2.创建数据库
/**
* NSString *dbPath = [NSHomeDirectory() stringByAppendingString:@"/Documents/favorite.db"];
NSLog(@"dbPath: %@", dbPath);
_fmdb = [[FMDatabase alloc]initWithPath:dbPath];
[_fmdb open];
*/
// 3.根据条件查询数据库中的某一天数据
/**
* NSString *strSql = @"select appId from FavoriteInfo where appId=?";
FMResultSet *resultSet = [_fmdb executeQuery:strSql, appId];
if (!resultSet) {
NSLog(@"查表出错:%@", _fmdb.lastErrorMessage);
return NO;
}
if ([resultSet next]) {
return YES;
}
return NO;
*/
/**
* NSString *strSql = @"delete from FavoriteInfo where appId=?";
[_fmdb executeUpdate:strSql, appId]
*/
/**
* NSString *strSql = @"delete from FavoriteInfo";
[_fmdb executeUpdate:strSql]
*/
// 6.插入数据
/** NSString *strSql = @"insert into FavoriteInfo(appId, name, appType, iconUrl) values(?, ?, ?, ?)";
// - 这个是给二进制的数据类型赋值
@"INSERT INTO Member (Name, Age, Sex, Height, Weight, Photo) VALUES (?,?,?,?,?,?)"
[_fmdb executeUpdate:strSql, model.applicationId, model.name, model.appType, model.iconUrl]
*/
// 7.查询全部表数据
/** NSString *strSql = @"select * from FavoriteInfo";
[_fmdb executeQuery:strSql]
*/