从 Xcode 中将数据添加到 SQLite3 DB

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9038602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 23:07:58  来源:igfitidea点击:

Adding data to SQLite3 DB from within Xcode

objective-cxcodesqlitesqlitemanager

提问by Solid I

I am trying to add 3 pieces of data to a SQLite3 DB. With help from a tutorial, I'm almost there. Below is my code.

我正在尝试将 3 条数据添加到 SQLite3 DB。在教程的帮助下,我快到了。下面是我的代码。

I am receiving what I would expect from the NSLogs. I find the DB without problem, I compile the statement to send to the DB without problem, but when the app gets to sqlite3_prepare_v2(database, sqlstatement, -1, &compliedstatement, NULL)==SQLITE_OKI am expecting the data to be added to the DB, but it isn't, and I'm also expecting to display a UIAlertViewto tell the user ERROR os SUCCESS. I hope you can see what I do not.

我收到了我对NSLogs. 我发现数据库没有问题,我编译语句以毫无问题地发送到数据库,但是当应用程序到达时,sqlite3_prepare_v2(database, sqlstatement, -1, &compliedstatement, NULL)==SQLITE_OK我希望将数据添加到DB,但事实并非如此,我也希望显示aUIAlertView告诉用户 ERROR os SUCCESS。我希望你能看到我看不到的东西。

- (IBAction)addData:(id)sender {
    NSString *n = [[NSString alloc] initWithString:[name text]];
    NSString *a = [[NSString alloc] initWithString:[age text]];
    NSString *c = [[NSString alloc] initWithString:[color text]];
    NSLog(@"%@ - %@ - %@",n,a,c);
    [self insertDataName:n Age:a Color:c];
}

This NSLogreturns the text properties as expected.

NSLog将按预期返回文本属性。

- (IBAction)hide:(id)sender {
    [name resignFirstResponder];
    [age resignFirstResponder];
    [color resignFirstResponder];

}



- (void)viewDidLoad
{
    [super viewDidLoad];
    DBName = @"mydatabase.sqlite";
    NSArray *documentsPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentsPaths objectAtIndex:0];
    DBPath = [documentsDir stringByAppendingPathComponent:DBName];

}


-(void)checkAndCreateDB {
    BOOL Success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    Success = [fileManager fileExistsAtPath:DBPath];

    if(Success) {
        NSLog(@"DB Found");    
        return;
    }

    NSLog(@"DB Not Found");
    NSString *databasePathFromApp = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:DBName];
    [fileManager copyItemAtPath:databasePathFromApp toPath:DBPath error:nil];

}

This NSLogreturns DB Found

NSLog返回DB Found

-(void)insertData Name:(NSString*)n Age:(NSString*)a Color:(NSString*)c {
    [self checkAndCreateDB];
    sqlite3 *database;
    if (sqlite3_open([DBPath UTF8String],&database)==SQLITE_OK) {
        NSString *statement;
        sqlite3_stmt *compliedstatement;
        statement = [[NSString alloc] initWithFormat:@"insert into table1 values ('%@', '%@', '%@')",n,a,c];
        const char *sqlstatement = [statement UTF8String];
        NSLog(@"%@",statement);

        if (sqlite3_prepare_v2(database, sqlstatement, -1, &compliedstatement, NULL)==SQLITE_OK) {

        if (SQLITE_DONE!=sqlite3_step(compliedstatement)) {
            NSAssert1(0, @"Error by inserting '%s'", sqlite3_errmsg(database));
            UIAlertView *AlertOK = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"Error by inserting" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];     

            [AlertOK show];

        }
        else {
            UIAlertView *AlertOK = [[UIAlertView alloc] initWithTitle:@"Success!" message:@"Data successfully inserted" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];             
            [AlertOK show];
            }
        }
        sqlite3_finalize(compliedstatement);

    }
    sqlite3_close(database);

}

And the last NSLogabove displays insert into table1 values ('n', 'a', 'c')as I would expect.

NSLog上面的最后一个显示insert into table1 values ('n', 'a', 'c')正如我所期望的那样。

Something is going wrong upon insertion and I can't figure it out.

插入时出现问题,我无法弄清楚。

FYI the DB was created using SQLiteManager. SS below:

仅供参考,数据库是使用 SQLiteManager 创建的。SS以下:

SQLiteManager table1 SS

SQLiteManager table1 SS

采纳答案by Byte

Ok, Are you working on a simulator or an iDevice? In iDevice, you cannot create an external SQL database (at least to my knowledge). You have to create it dynamically because of the sandboxing. "FYI the DB was created using SQLiteManager." Check on that.

好的,你是在模拟器还是 iDevice 上工作?在 iDevice 中,您不能创建外部 SQL 数据库(至少据我所知)。由于沙箱,您必须动态创建它。“仅供参考,数据库是使用 SQLiteManager 创建的。” 检查一下。

If that was not the problem try changing your code from "prepare ..." to "execute"

如果这不是问题,请尝试将代码从“准备...”更改为“执行”

From...

从...

if (sqlite3_prepare_v2(database, sqlstatement, -1, &compliedstatement, NULL)==SQLITE_OK) {

    if (SQLITE_DONE!=sqlite3_step(compliedstatement)) {
        NSAssert1(0, @"Error by inserting '%s'", sqlite3_errmsg(database));
        UIAlertView *AlertOK = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"Error by inserting" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];     

        [AlertOK show];

    }
    else {
        UIAlertView *AlertOK = [[UIAlertView alloc] initWithTitle:@"Success!" message:@"Data successfully inserted" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];             
        [AlertOK show];
        }
    }
    sqlite3_finalize(compliedstatement);

To...

到...

    sqlite3_exec(database, [sqlstatement UTF8String], NULL, NULL, &error);
    sqlite3_exec(database, [sqlstatement UTF8String], NULL, NULL, &error);

Do a log on "error" because that is very essential.

登录“错误”,因为这是非常必要的。

if you wanted to pop a UIAlert do this

如果您想弹出 UIAlert,请执行此操作

 if (error !=nil)
    //show alert for error
 else
    //show alert for success