以编程方式创建2个表,sqlite objective c不起作用

时间:2017-07-10 13:44:22

标签: ios objective-c sqlite

我正在使用xcode目标c,我有以下代码:

- (void)initializationDatabase {
    NSString *sql =
    @"CREATE TABLE albums("
    "albumid INTEGER PRIMARY KEY AUTOINCREMENT,"
    "directory CHAR(20) NOT NULL,"
        "albumname CHAR(32) NOT NULL,"
        "count INT NOT NULL,"
        "orderid INT NOT NULL"
        ");"

        "CREATE TABLE photos("
        "photoid INTEGER PRIMARY KEY AUTOINCREMENT,"
        "albumid INTEGER NOT NULL DEFAULT 0,"
        "filename CHAR(50) NOT NULL DEFAULT \"\","
        "originalname CHAR(50) DEFAULT \"\","
        "addtime INTEGER NOT NULL DEFAULT 0,"
        "createtime INTEGER NOT NULL DEFAULT 0,"
        "filesize INTEGER NOT NULL DEFAULT 0,"
        "filetype TINYINT NOT NULL DEFAULT 0"
        ");";
        FMDatabase *database = [FMDatabase databaseWithPath:[self databaseFilePath]];
        [database open];
        [database executeUpdate:sql];
        [database close];
    }


    - (void)createCopyOfDatabaseIfNeeded {
        // First, test for existence.
        BOOL success;
        NSError *error;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSLog(@"%@",[self databaseFilePath]);

        success = [fileManager fileExistsAtPath:[self databaseFilePath]];
        if (success){
            return;
        }else{
            [fileManager createFileAtPath:[self databaseFilePath] contents:nil attributes:nil];
        }
        // The writable database does not exist, so copy the default to the appropriate location.
        NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"db.sqlite"];
        success = [fileManager copyItemAtPath:defaultDBPath toPath:[self databaseFilePath] error:&error];
        if (!success) {
            NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
        }
    }

-(NSString *)databaseFilePath{
    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docsPath = [paths objectAtIndex:0];
    NSString *dbPath = [docsPath stringByAppendingPathComponent:@"FakeCalculator.sqlite"];
    return  dbPath;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Function called to create a copy of the database if needed.
    [[SQLiteUtilities sharedSQLiteManager] createCopyOfDatabaseIfNeeded];
    [[SQLiteUtilities sharedSQLiteManager] initializationDatabase];

    return YES;
}

但我的问题是这个代码只创建表专辑而不是表格照片,当我尝试插入删除或任何表格照片我得到表不存在错误,当我打开db.sqlite文件我只找到一个表(专辑),任何想法?

1 个答案:

答案 0 :(得分:1)

[database executeUpdate:sql];

执行单个SQL语句。

要执行多个语句,请使用executeStatements: