Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Iphone 在sqlite中的同一数据库中插入多个表_Iphone_Objective C_Sqlite - Fatal编程技术网

Iphone 在sqlite中的同一数据库中插入多个表

Iphone 在sqlite中的同一数据库中插入多个表,iphone,objective-c,sqlite,Iphone,Objective C,Sqlite,在创建Iphone应用程序时,我常常在不同的数据库上执行INSERT查询。 但当我尝试将数据插入同一个数据库时,断言失败了。 我正在读取两个不同的XML URL,并尝试创建数据,然后在通过创建DB读取数据时将数据插入表中。有人知道为什么这会显示出错误吗? 我使用SQLITE在DB上插入了以下代码: -(void) insertProductTable:(NSMutableArray *)Dict{ [Dict retain]; NSArray *paths = NSSearchPathFor

在创建Iphone应用程序时,我常常在不同的数据库上执行INSERT查询。 但当我尝试将数据插入同一个数据库时,断言失败了。 我正在读取两个不同的XML URL,并尝试创建数据,然后在通过创建DB读取数据时将数据插入表中。有人知道为什么这会显示出错误吗? 我使用SQLITE在DB上插入了以下代码:

  -(void) insertProductTable:(NSMutableArray *)Dict{
[Dict retain];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:@"product.sql"];
NSInteger i;

if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {

    const char * insert_product_sql = "INSERT OR REPLACE INTO test(ID,KEY ) VALUES (?,?)" ;
    if(sqlite3_prepare_v2(database, insert_product_sql, -1, &product_statement, nil) != SQLITE_OK){
        NSAssert1(0, @"Error: failed to prepare insert_product_sql: '%s'.", sqlite3_errmsg(database));
    }

    for (i = 0; i < [self.array count]; i++) {
     sqlite3_bind_text(product_statement, 1, [[Dict valueForKey:@"ID"] UTF8String] ,-1, SQLITE_TRANSIENT);
     sqlite3_bind_text(product_statement, 2, [[Dict valueForKey:@"KEY"] UTF8String] ,-1, SQLITE_TRANSIENT);
    }

    if (sqlite3_step(product_statement) != SQLITE_DONE) {
        NSAssert(0,@"Error updating table");
    }

    [Dict release]; Dict = 0;
    sqlite3_finalize(product_statement);
    sqlite3_close(database);

}
}
-(void)insertProductTable:(NSMutableArray*)Dict{
[保留意见];
NSArray*Path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,是);
NSString*documentsDirectory=[paths objectAtIndex:0];
NSString*dbPath=[DocumentsDirectoryStringByAppendingPathComponent:@“product.sql”];
恩森特格尔一世;
if(sqlite3_打开([dbPath UTF8String],&database)==SQLITE_确定){
const char*insert_product_sql=“插入或替换到测试(ID,键)值(?,)”;
if(sqlite3\u prepare\u v2(数据库,insert\u product\u sql,-1,&product\u语句,nil)!=SQLITE\u OK){
NSAssert1(0,@“错误:无法准备插入\u产品\u sql:“%s.”,sqlite3\u errmsg(数据库));
}
对于(i=0;i<[self.array count];i++){
sqlite3绑定文本(产品语句,1,[[Dict valueForKey:@“ID”]UTF8String],-1,SQLITE瞬时);
sqlite3绑定文本(产品语句,2,[[Dict valueForKey:@“KEY”]UTF8String],-1,SQLITE瞬态);
}
if(sqlite3\u步骤(产品语句)!=SQLITE\u完成){
NSAssert(0,@“错误更新表”);
}
[Dict release];Dict=0;
sqlite3_最终确定(产品_声明);
sqlite3_关闭(数据库);
}
}
我有下面的方法,它执行不同的插入函数,但不同的表,但在这个阶段,它不允许我插入抛出断言失败。这两个方法都由不同的类调用

    -(void) insertTable:(NSMutableArray *)Dict{
[Dict retain];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:@"product.sql"];
NSInteger i;

if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {

    const char * insert_sql = "INSERT OR REPLACE INTO test1(Term,Value ) VALUES (?,?)" ;
    if(sqlite3_prepare_v2(database, insert_sql, -1, &product_statement, nil) != SQLITE_OK){
        NSAssert1(0, @"Error: failed to prepare insert_sql: '%s'.", sqlite3_errmsg(database));
    }

    for (i = 0; i < [self.arayList count]; i++) {
     sqlite3_bind_text(product_statement, 1, [[Dict valueForKey:@"TERM"] UTF8String] ,-1, SQLITE_TRANSIENT);
     sqlite3_bind_text(product_statement, 2, [[Dict valueForKey:@"VALUE"] UTF8String] ,-1, SQLITE_TRANSIENT);
    }

    if (sqlite3_step(product_statement) != SQLITE_DONE) {
        NSAssert(0,@"Error updating table");
    }

    [Dict release]; Dict = 0;

    sqlite3_finalize(product_statement);
    sqlite3_close(database);

}
}
-(void)insertTable:(NSMutableArray*)Dict{
[保留意见];
NSArray*Path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,是);
NSString*documentsDirectory=[paths objectAtIndex:0];
NSString*dbPath=[DocumentsDirectoryStringByAppendingPathComponent:@“product.sql”];
恩森特格尔一世;
if(sqlite3_打开([dbPath UTF8String],&database)==SQLITE_确定){
const char*insert_sql=“插入或替换为test1(术语、值)值(?,)”;
if(sqlite3\u prepare\u v2(数据库,insert\u sql,-1,&product\u语句,nil)!=SQLITE\u OK){
NSAssert1(0,@“错误:无法准备插入sql:“%s.”,sqlite3_errmsg(数据库));
}
对于(i=0;i<[self.arayList count];i++){
sqlite3绑定文本(产品语句,1,[[Dict valueForKey:@“TERM”]UTF8String],-1,SQLITE瞬态);
sqlite3绑定文本(产品语句,2,[[Dict valueForKey:@“VALUE”]UTF8String],-1,SQLITE瞬时);
}
if(sqlite3\u步骤(产品语句)!=SQLITE\u完成){
NSAssert(0,@“错误更新表”);
}
[Dict release];Dict=0;
sqlite3_最终确定(产品_声明);
sqlite3_关闭(数据库);
}
}
@lifemoveson

我用你的代码来调试,发现这个函数

sqlite3_prepare_v2(database, insert_product_sql, -1, &product_statement, nil)
每次返回1,它对应于所需位置缺少的数据库

我建议你做一个这样的函数

-(void)checkAndCreateDatabase{
    databaseName = @"MasterDB.sqlite";
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
    NSLog(@"database path %@",databasePath);
    BOOL success;

    // Create a FileManager object, we will use this to check the status
    // of the database and to copy it over if required
    NSFileManager *fileManager = [NSFileManager defaultManager];

    // Check if the database has already been created in the users filesystem
    success = [fileManager fileExistsAtPath:databasePath];

    // If the database already exists then return without doing anything
    if(success) return;

    // If not then proceed to copy the database from the application to the users filesystem

    // Get the path to the database in the application package
    NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];

    // Copy the database from the package to the users filesystem
    [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
    //[fileManager release];

    // Now we can add new table

    sqlite3 *database;
    sqlite3_stmt *statement; 
    if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
    {

        NSString *sqlQuery = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS tbl_Login (userId integer PRIMARY KEY,userName text,password text);"] ;
        const char *create_stmt = [sqlQuery UTF8String];
        sqlite3_prepare_v2(database, create_stmt, -1, &statement, NULL);

        if(sqlite3_step(statement)==SQLITE_DONE) 
        {
            NSLog(@"Table created");            
        }
        else 
        {
            NSLog(@"Table could not be created");
        }   
        // Release the compiled statement from memory
        sqlite3_finalize(statement);    
        sqlite3_close(database);
    }
}
它设置类变量databasePath,并确保在运行任何数据库查询之前,数据库实际存在于应用程序的文档目录中。您可以在应用程序委托中调用此函数

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
//Other code 
[self checkAndCreateDatabase];

}
当您进行任何数据库调用时,请使用

const char *dbpath = [databasePath UTF8String];
    if (sqlite3_open(dbpath , &database) == SQLITE_OK) {
//Code to perform insert operations
 }
我建议您为执行的所有数据库操作编写一个单独的类,并调用class函数以实现所需的功能。这将节省您重写代码的时间

您可以使用FMDB包装器来实现这一点


希望这有帮助:-)

感谢Rahul指出错误和解决方案。还有一个小问题。如何在checkAndCreateDatabase中添加创建表查询,或者需要为创建查询添加新函数。另外,我在不同的类中有两个不同的函数,用于在同一个数据库中执行两个插入查询。我怎样才能做到呢?谢谢你的帮助,拉胡尔。我确实使用了你提出的逻辑,但我有一个简短的问题。正如你所看到的,我有两个不同的插入函数,都在不同的类中。我如何将数据库指向那个目录?此外,我以前从未与FMDB合作过,也不知道它是如何工作的。我不确定我是否会使用它。我建议FMDB看看函数本身。在这里,您必须手动提取插入函数中特定键的值。调用一个有两个参数的函数怎么样。。NSString,即您的查询和包含参数的NSArray,即键的对象,如@“TERMS”、“ID”等。Rest分配将由FMDB负责。这就是FMDB的优点。您可以搜索使用FMDB的好教程。