在iphone中使用sqlite在同一数据库的第二个表上插入数据

时间:2014-08-13 18:29:07

标签: ios sqlite

我成功地能够使用sqlite在同一个数据库中创建多个表,但无法从第二个表中插入数据。如果我在单独的数据库中使用这些表,它工作正常。有人可以指导我吗?同一数据库中多个表的任何示例代码或教程也会对我有所帮助。

1 个答案:

答案 0 :(得分:0)

这是用于在位于一个数据库中的两个不同表中插入数据的示例代码。 accelerometerData timeData tcDB.db 中的表格(我使用FMDB框架与数据库进行通信)

#import "TCDBManager.h"
#import "FMDatabase.h"

@implementation TCDBManager
{
    NSString *databaseName;
    NSString *databasePath;
}

+ (TCDBManager *)sharedClient
{
    static TCDBManager *_sharedClient = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _sharedClient = [[self alloc]init];

    });
    return _sharedClient;
}

-(id)init
{
   self = [super init];
    if (self) {

        databaseName = @"tcDB.db";

        NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentDir = [documentPaths objectAtIndex:0];
        databasePath = [documentDir stringByAppendingPathComponent:databaseName];

        [self createAndCheckDatabase];

    }
    return self;
}

-(void)createAndCheckDatabase
{
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    success = [fileManager fileExistsAtPath:databasePath];

    if(success) return;

    NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];

    [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}

-(BOOL)insertX:(float)x Y:(float)y Z:(float)z horizontalAcceleration:(float)horizontalAcceleration latitude:(float)latitude longitude:(float)longitude speed:(float)speed activity:(int)activity time:(int)time
{
    FMDatabase *db = [FMDatabase databaseWithPath:databasePath];

    [db open];
    [db beginTransaction];
    BOOL success =  [db executeUpdateWithFormat:@"INSERT INTO accelerometerData (x,y,z,horizontalAcceleration,lat,long,speed,time,activity) VALUES (%f,%f,%f,%f,%f,%f,%f,%d,%d);",
                 x,
                 y,
                 z,
                 horizontalAcceleration,
                 latitude,
                 longitude,
                 speed,
                 time,
                 activity,
                 nil];

   [db commit];

    [db close];
    return success;
}

-(BOOL)insertTime:(int)time
{
    FMDatabase *db = [FMDatabase databaseWithPath:databasePath];

    [db open];
    [db beginTransaction];
    BOOL success =  [db executeUpdateWithFormat:@"INSERT INTO timeData (timeSinceLastUpdate) VALUES (%d);",time,nil];

    [db commit];

    [db close];
    return success;

}

-(void)clearData
{
    FMDatabase *db = [FMDatabase databaseWithPath:databasePath];

    [db open];
    [db beginTransaction];
    BOOL success =  [db executeUpdateWithFormat:@"DELETE FROM accelerometerData"];

    [db commit];
    [db close];
}

@end