Sqlite创建数据库

时间:2013-12-11 20:42:37

标签: objective-c sqlite

我是sqlite的新手,并且我已经花了几天时间尝试按照教程,但它不想添加我的数据库和表格。如果没有添加表格,它会给我提醒我。 "尚未创建TABLE"

我没有得到任何xcode错误,所以它可能是我猜的代码。有人有什么建议吗?

viewcontroller.h

@property (retain, nonatomic) NSString *databaseName, *tableName;
@property (readwrite, nonatomic) int numberOfRows;
@property (readwrite, nonatomic) NSMutableArray *dataList;
@property (readwrite, nonatomic) BOOL table_ok, db_open_status;
@property (retain, nonatomic) NSArray *my_columns_names; 

viewcontroller.h

[super viewDidLoad];
dataList = [[NSMutableArray alloc]init];
numberOfRows = 0;
databaseName = @"mysampledatabase";
tableName = @"mypeople";
db_open_status = NO;
table_ok = NO;
my_columns_names = [[NSArray alloc]initWithObjects:@"hometeam",@"awayteam",@"homeplayers",@"homefouls",@"awayplayers",@"awayfouls",@"period",@"time",@"homescore",@"awayscore", nil];
if ([self openDBWithSQLName:databaseName]) {
    db_open_status = YES;
    if (![self createTable:tableName WithCoulumns:my_columns_names]) {
        UIAlertView *av = [[UIAlertView alloc]initWithTitle:@"Warning" message:@"the TABLE has not been created" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
        [av show];
    } else {
        table_ok = YES;
    }
}


-(BOOL)openDBWithSQLName:(NSString *)sqlname{
    BOOL is_Opened = NO;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *my_sqlfile = [[paths objectAtIndex:0] stringByAppendingPathComponent:sqlname];
    if (sqlite3_open([my_sqlfile UTF8String], &dbname) ==SQLITE_OK) {
        is_Opened = YES;
    }
    return is_Opened;

}


-(BOOL)createTable:(NSString *)tablename WithCoulumns:(NSArray *)columnNames{
    BOOL has_beencreated = NO;
    NSString *fieldset = @"";
    char *err;
    for (int a=0; a<[columnNames count]; a++){

        NSString *columnSet = [NSString stringWithFormat:@"'%@' TEXT", [columnNames objectAtIndex:a]];
        fieldset = [fieldset stringByAppendingString:columnSet];
        if (a<([columnNames count]-1)) {
            fieldset = [fieldset stringByAppendingString:@" ,"];
        }

    }
    NSString *sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' (ID INTEGER PRIMARY KEY AUTOINCREMENT,%@", tableName, fieldset];
    if (sqlite3_exec(dbname, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK) {
        sqlite3_close(dbname);
    } else {
        has_beencreated = YES;
    }
    return has_beencreated;
}

1 个答案:

答案 0 :(得分:0)

我想我已经找到了“你还没有创建过TABLE”的问题(我也做了!)。如果添加此代码,则在分配 * sql 之前的createTable:方法中: fieldset=[fieldset stringByAppendingString:@")"];

fiedlset通过它未命中的右括号来实现。 您可以通过在此处放置一个断点来自行检查:

has_beencreated = YES;

运行应用并检查变量&amp; err

希望它有所帮助!