#define KDataBasePath @“...”
FMDatabase *db = [FMDatabase databaseWithPath:KDataBasePath];```
1、打开数据库
[db open]
2、creat insert 用同一方法:将SQL语句转化为NSString
[db executeUpdate:SQLCommandString];
3、select 查询用query 返回值:FMResultSet类型 是个集合
FMResultSet *result = [db executeQuery:SQLCommandString];
if ([result next]) {
NSLog(@"select success");
//拿出查询的字段数据
[result stringForColumn:@"name"];
}
4、关闭数据库
[db close];
例子:
打开数据库
#define KDataBasePath @“...”
FMDatabase *db = [FMDatabase databaseWithPath:KDataBasePath];
if (![db open]) {
NSLog(@"could not open db");
return;
}else {
NSLog(@"open db");
}```
创建数据表
-(void)creatTableWithTableName
{
NSString *creatString = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS 'user' ('id' INTEGER PRIMARY KEY AUTOINCREMENT, 'name' TEXT, 'password' TEXT)"];
BOOL result = [db executeUpdate:creatString];
if (result) {
NSLog(@"tabel success");
}else {
NSLog(@"tabel fail");
}
}
查询数据表是否存在
-(void)queryTable:(NSString *)tableName
{
if ([db executeQuery:@"select count(*) as 'count' from sqlite_master where type = 'table' and name = %@",tableName]) {
NSLog(@"tabel 已存在");
}else {
NSLog(@"tabel 不存在");
}
}
插入一条数据
-(BOOL)insertDataWithId:(NSInteger)user_id
Name:(NSString *)name
Password:(NSString *)password
{
//有问题------
BOOL result = [db executeUpdate:@"insert into user (name,password) values (?,?)",name,password];
if (result) {
NSLog(@"insert success");
}else {
NSLog(@"insert fail");
}
return result;
}
select选择数据
-(BOOL)selectTableWithUserName:(NSString *)name Password:(NSString *)password
{
BOOL resultSelect = NO;
NSString *selectString = [NSString stringWithFormat:@"select *from 'user' where name = '%@' and password = '%@'",name,password];
FMResultSet *result = [db executeQuery:selectString];
if ([result next]) {
resultSelect = YES;
NSLog(@"select success");
NSLog(@"%@",[result stringForColumn:@"name"]);
}else{
NSLog(@"select fail");
}
return resultSelect;
}
关闭数据库
-(void)closeDataBase
{
if (![db close]) {
NSLog(@"数据库关闭异常,请检查");
return;
}else {
NSLog(@"关闭成功");
}
}