美文网首页
FMDB数据库的使用

FMDB数据库的使用

作者: Django_Monstar | 来源:发表于2016-05-07 12:47 被阅读111次

获取本地沙盒路径

NSString *str = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) .firstObject];

创建数据数据库


if([fileManager fileExistsAtPath:self.dbPath] ==YES) {FMDatabase*db = [FMDatabase databaseWithPath:self.dbPath];

if([db open]) {

//创建名字为myTable的表

NSString*sql =@"CREATE TABLE 'myTable' ('id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,'name' VARCHAR (30),'password' VARCHAR (30))";

BOOL exsit = [db executeQuery:sql];

if(!exsit) {

//创建失败

}

else{

//创建成功

}

[db close];

}

else{

//打开db失败

}

}

添加数据到数据库

FMDatabase*db = [FMDatabase databaseWithPath:self.dbPath];

if([db open]) {

NSString*nameStr =@"输入的名字";

NSString*passwordStr =@"输入的密码";

NSString*sql = [NSString stringWithFormat:@"inset into myTable (name,password) values(%@, %@)",nameStr,passwordStr];

BOOL res = [db executeUpdate:sql];

if(res) {

//插入成功

}

else{

//插入失败

}

[db close];

}

查询数据

FMDatabase*db = [FMDatabase databaseWithPath:self.dbPath];

if([db open]) {

NSString*sql =@"select * from myTable";

FMResultSet*rs = [db executeQuery:sql];

while([rs next]) {

int userId = [rs intForColumn:@"id"];

NSString*name = [rs stringForColumn:@"name"];

NSString*pass = [rs stringForColumn:@"password"];

//获取数据库信息

}

[db close];

}

清空数据库

FMDatabase*db = [FMDatabase databaseWithPath:self.dbPath];

if([db open]) {

NSString*sql =@"delete from myTable";

BOOL res =[db executeUpdate:sql];

if(res) {

//清空成功

}else{

//清空失败

}

[dbclose];

}

使用FMDatabaseQueue更新数据

FMDatabaseQueue*queue = [FMDatabaseQueuedatabaseQueueWithPath:self.dbPath];'

[queueinDatabase:^(FMDatabase*db) {

NSString*sql =@"insert into myTable (name,password) values(?,?)";

BOOL res = [db executeUpdate:sql,@"name",@"pass"];

if(res) {

//插入成功

}

else{

//插入失败

}

}];

相关文章

网友评论

      本文标题:FMDB数据库的使用

      本文链接:https://www.haomeiwen.com/subject/dqzjrttx.html