//swift let documentsFolder =NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] asString let path = documentsFolder.stringByAppendingPathComponent("test.sqlite") let database =FMDatabase(path: path)
//OC if (![db open]) { NSLog(@"Could not open db."); } NSString *sql = @"create table test(x text, y text, z text)"; if (![db executeUpdate:sql] ) { NSLog(@"create table failed: %@",[db lastErrorMessage]); } [db close];
1 2 3 4 5 6 7
//swift if database.open() { if!database.executeUpdate("create table if not exists test(x text, y text, z text)", withArgumentsInArray: nil) { println("create table failed: \(database.lastErrorMessage())") } database.close() }
增加一行数据:
1 2 3 4 5 6 7 8
//OC if (![db open]) { NSLog(@"Could not open db."); } if (![db executeUpdate:@"insert into test(x, y, z) values (? , ?, ?)",@"a",@"b",@"c"]) { NSLog(@"insert 1 table failed: %@", [db lastErrorMessage]); } [db close];
1 2 3 4 5 6 7
//swift if database.open() { if!database.executeUpdate("create table if not exists test(x text, y text, z text)", withArgumentsInArray: nil) { println("create table failed: \(database.lastErrorMessage())") } database.close() }
//OC if (![db open]) { NSLog(@"Could not open db."); } if (![db executeUpdate:@"delete from test where x = ?",@"a"]) { NSLog(@"delete failed: %@",[db lastErrorMessage]); } [db close];
1 2 3 4 5 6 7 8
//swift if database.open(){ if!database.executeUpdate("delete from test where x = ?", withArgumentsInArray: ["a"]){ println("delete failed: \(database.lastErrorMessage())") } database.close() }
查询:
1 2 3 4 5 6 7 8 9 10 11 12
//OC if (![db open]) { NSLog(@"Could not open db."); } FMResultSet *rs = [db executeQuery:@"select x, y, z from test"]; while (rs.next) { NSString *x = [rs stringForColumn:@"x"]; NSString *y = [rs stringForColumn:@"y"]; NSString *z = [rs stringForColumn:@"z"]; NSLog(@"x = %@; y = %@; z = %@",x,y,z); } [db close];
1 2 3 4 5 6 7 8 9 10 11 12 13 14
//swift if database.open(){ iflet rs = database.executeQuery("select x, y, z from test", withArgumentsInArray: nil) { while rs.next() { let x = rs.stringForColumn("x") let y = rs.stringForColumn("y") let z = rs.stringForColumn("z") println("x = \(x); y = \(y); z = \(z)") } } else { println("select failed: \(database.lastErrorMessage())") } database.close() }
修改:
1 2 3 4 5 6 7 8
//OC if (![db open]) { NSLog(@"Could not open db."); } if (![db executeUpdate:@"update test set y = ? where x = ?",@"00",@"a"]) { NSLog(@"update falied: %@" , [db lastErrorMessage]); } [db close];
1 2 3 4 5 6 7 8
//swift if database.open(){ if!database.executeUpdate("update test set y = ? where x = ?", withArgumentsInArray: ["00","a"]){ println("update failed: \(database.lastErrorMessage())") } database.close() }