【问题标题】:iPHONE SDK- sqlite , how do i do an insert statementiPHONE SDK-sqlite,我如何做一个插入语句
【发布时间】:2023-03-23 01:15:01
【问题描述】:

我有一个数据库,位于 Application/iPhoneSimulator/3.2/Applications/etc/Documents

我的方法下有这段代码

    databaseName = @"database.sql";
NSArray *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory.NSUserDomainMask,YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];

如何使用变量/数组进行插入。 就像是 "INSERT INTO TABLE (COLUMN) VALUES ('%@'),[appDelegate.variable objectAtIndex:0];

【问题讨论】:

    标签: iphone


    【解决方案1】:

    我坚持让你通过this question。 首先将数据库从主包复制到应用程序的文档目录。 您可以按照下面的代码来实现它。

        NSString *databaseFile=[[NSBundle mainBundle] pathForResource:kDataBaseName ofType:kDataBaseExt];
    
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
        NSString *dbPath=[basePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@",kDataBaseName,kDataBaseExt]];
        NSFileManager *fm=[NSFileManager defaultManager];
    
        if(![fm fileExistsAtPath:dbPath]){
            [fm copyItemAtPath:databaseFile toPath:dbPath error:nil];
        }
    
        [fm release];
    
        self.dataBasePath=dbPath;
    

    我直接向您提供我的项目代码。如有任何疑问,请添加评论。 我已经添加了 cmets 进行解释。

    // function with multiple arguments which is going to be used for inserting into table.
    +(void)insertBuilding:(NSString*)BName streetNo:(NSInteger)streetNo streetName:(NSString*)streetName streetDir:(NSString*)streetDir muni:(NSString*)muni province:(NSString*)province bAccess:(NSString*)bAccess bType:(NSString*)bType amnity:(NSString*)amnity latitude:(NSString*)latitude longitude:(NSString*)longitude imageName:(NSString*)imageName {
        // application delegate where I have saved my database path.
        BuildingLocatorAppDelegate *x=(BuildingLocatorAppDelegate *)[[UIApplication sharedApplication]delegate];
        sqlite3 *database; // database pointer
        // verifying if database successfully opened from path or not.
        // you must open database for executing insert query    
        // i have supplied database path in argument 
        // opened database address will be assigned to database pointer.
        if(sqlite3_open([[x dataBasePath] UTF8String],&database) == SQLITE_OK) {
            // creating a simple insert query string with arguments.
            NSString *str=[NSString stringWithFormat:@"insert into buildingDtl(b_name,streetNo,streetName,streetDir,muni,province,b_access,b_type,aminity,latitude,longitude,b_image) values('%@',%i,'%@','%@','%@','%@','%@','%@','%@','%@','%@','%@')",BName,streetNo,streetName,streetDir,muni,province,bAccess,bType,amnity,latitude,longitude,imageName];
            // converting query to UTF8string.
            const char *sqlStmt=[str UTF8String];       
            sqlite3_stmt *cmp_sqlStmt;
            // preparing for execution of statement.
            if(sqlite3_prepare_v2(database, sqlStmt, -1, &cmp_sqlStmt, NULL)==SQLITE_OK) {
                int returnValue = sqlite3_prepare_v2(database, sqlStmt, -1, &cmp_sqlStmt, NULL);
                ((returnValue==SQLITE_OK) ?  NSLog(@"Success") :  NSLog(@"UnSuccess") );
                    // if NSLog -> unsuccess - that means - there is some problem with insert query.
                sqlite3_step(cmp_sqlStmt);
            }
            sqlite3_finalize(cmp_sqlStmt);
        }
        sqlite3_close(database);
        // please don't forget to close database.
    }
    

    【讨论】:

    • 您好,我试过这个并且在 NSLOG 中取得了成功。但是,当我再次尝试读取数据库时,值不存在
    • databaseName = @"TestDatabase.sql"; //获取文档的路径 NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDir = [documentPaths objectAtIndex:0]; databasePath = [documentsDir stringByAppendingPathComponent:databaseName]; UIAlertView *视图; // 设置数据库对象 sqlite3 *database; appDelegate.dBCount = [[NSMutableArray alloc]init]; // 从用户文件系统打开数据库 if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
    • // 设置 SQL 语句并编译它以加快访问速度 const char *sqlStatement = "Select EntryID From XMLEntryID ORDER BY xeID DESC LIMIT 1 "; sqlite3_stmt *compiledStatement; if(sqlite3_prepare_v2(database, sqlStatement,-1, &compiledStatement, NULL) == SQLITE_OK) { // 遍历结果并将它们添加到 feeds 数组 while(sqlite3_step(compiledStatement) == SQLITE_ROW) { // 从结果行 NSString *aEntryID = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
    • //将用户对象添加到 users Array 和分别 [appDelegate.dBCount addObject:aEntryID]; view = [[UIAlertView alloc] initWithTitle:@"A Message" message:aEntryID delegate: self cancelButtonTitle:@"Yay.!"其他按钮标题:无]; [查看节目]; [查看自动释放]; [aEntryID 发布];返回; } } // 从内存中释放编译语句 sqlite3_finalize(compiledStatement); } sqlite3_close(数据库);
    • 这是我的方法中的代码,用于读取我拥有的最新值的数据库,但似乎没有插入这些值。
    【解决方案2】:
    +(NSString *)stringWithFormat:(NSString *)format parameters:...];
    
    NSString sql = [NSString stringWithFormat:@"INSERT INTO table VALUES('%@')", @"Hello, world!"];
    sqlite3_....
    

    【讨论】:

    • 在这种情况下,您可能希望通过用双单引号替换单引号来转义它们。
    【解决方案3】:

    将准备好的语句与bind_*() 函数(例如bind_text())或mprintf() 函数结合使用来插入字符串,有关详细信息,请参阅this question

    要获取原始 C 字符串,您可以在 NSString 上使用 -UTF8String-cStringUsingEncoding: 传递给这些函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-25
      • 1970-01-01
      相关资源
      最近更新 更多