iphone上的Sqlite“附近”语法错误

时间:2013-10-17 13:39:22

标签: ios sqlite

我正在我的iphone应用程序中尝试使用sqlite的问题。读取部分没问题,但是当我尝试使用UPADATE命令写入数据库时​​(我也尝试使用INSERT),sql语句给我回错了sqlite3_errmsg:

Failed. Error is:  near "UP": syntax error

代码是:

-(void)ratesInfotoDb:(NSString *)idx rate:(NSString*)rate{

    query =@"UPDATE rules set rate = 5 where _id = 1994";

    sqlite3_stmt *statement;
    sqlite3_prepare_v2(_database, [query UTF8String], SQLITE_OPEN_READWRITE, &statement, nil);

    if(sqlite3_step(statement) == SQLITE_DONE ) {
        NSLog(@"element added");
        }
    else{
        NSLog( @"Failed. Error is:  %s", sqlite3_errmsg(_database));
    }

    sqlite3_finalize(statement);
    sqlite3_close(_database);

}

查询命令“UPDATE rules set rate = 5 where _id = 1994”(直接在数据库上执行),有效,所以我认为查询是corect。

有人可以帮我吗?

3 个答案:

答案 0 :(得分:3)

问题很简单。您将错误的值传递给sqlite3_prepare_v2函数。第3个参数应表示查询字符串的长度。

SQLITE_OPEN_READWRITE的值为2,因此您声明查询只有2个字节长,这是不正确的。

将您的通话更改为sqlite3_prepare_v2,如下所示:

sqlite3_prepare_v2(_database, [query UTF8String], -1, &statement, nil);

传递-1告诉sqlite3_prepare_v2获取查询的实际长度(可能使用strlen)。

BTW - 始终检查sqlite3_prepare_v2的返回值,并确保它返回SQLITE_OK

答案 1 :(得分:1)

尝试使用此方法......

您的数据库未打开。请查看此方法以获取如何正确打开它的示例。

-(void)executeQuery:(NSString *)query
{
    sqlite3_stmt *statement;
    if(sqlite3_open([[self dataFilePath] UTF8String], &database) == SQLITE_OK)
    {
        if (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, NULL) == SQLITE_OK)
        {
            if (sqlite3_step(statement) != SQLITE_DONE)
            {
                sqlite3_finalize(statement);
            }
        }
        else
        {
            NSLog(@"query Statement Not Compiled");
        }

        sqlite3_finalize(statement);
        sqlite3_close(database);
    }
    else
    {
        NSLog(@"Data not Opened");
    }
}

答案 2 :(得分:-1)

         NSString *status;


    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];
    NSString *dbPath=[[NSString alloc]initWithString:[documentsDir stringByAppendingPathComponent:@"YOUR DATABASE NAME.sqlite"]];

    NSLog(@"Database Path %@",dbPath);

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

        NSLog(@"open");

        NSString *updateSQL = [NSString stringWithFormat: @"UPDATE rules set rate = 5 where _id = 1994"];

        const char *update_stmt = [updateSQL UTF8String];
        sqlite3_prepare_v2(database, update_stmt, -1, &statement, NULL);
        if (sqlite3_step(statement) == SQLITE_DONE)
        {
            status=@" Updated";
        }

        else
        {
            status=@"Error occured";
        }