如何从Sqlite数据库中获取数据?

时间:2017-08-22 06:46:54

标签: ios objective-c sqlite

我已经创建了sqlite db Table,如下所示

NSString * sqlStmt =@"CREATE TABLE IF NOT EXISTS SONGS (ID INTEGER PRIMARY KEY AUTOINCREMENT, SONGNAME TEXT UNIQUE NOT NULL,ALBUMNAME TEXT ,ARTIST TEXT ,SIZE FLOAT ,IMAGE BLOB)";

当我试图从这个表中获取数据时什么都没有

NSString *sqlQuery = [NSString stringWithFormat:
                @"SELECT ARTIST ,IMAGE FROM SONGS WHERE SONGNAME=kannulada"];

但是当iam试图通过id获取数据时,我得到了数据。

NSString *sqlQuery = [NSString stringWithFormat:
                @"SELECT ARTIST ,IMAGE FROM SONGS WHERE id=1"];

当我调试它时没有激活准备循环

-(NSMutableArray*)retrieveDataArrayWHICHISequql
{
  [dataArray removeAllObjects];
 sqlite3_stmt  *statement;

const char *dbpath = [databasePath UTF8String];

if (sqlite3_open(dbpath, &_SQliteDB) == SQLITE_OK)
{

    const char * selectQuery =[sqlQuery UTF8String];

    if (sqlite3_prepare_v2(_SQliteDB, selectQuery, -1, &statement, NULL)== SQLITE_OK)
    {
        while (sqlite3_step(statement)== SQLITE_ROW)
        {
            NSString * addressStr = [[NSString alloc]initWithUTF8String:(const char*)sqlite3_column_text(statement, 0)];

            NSString * phNumStr = [[NSString alloc]initWithUTF8String:(const char*)sqlite3_column_text(statement, 1)];

            //  NSString * nameStr = [[NSString alloc]initWithUTF8String:(const char*)sqlite3_column_text(statement, 2)];

            NSMutableDictionary * dataDict = [[NSMutableDictionary alloc]init];
            [dataDict setObject:addressStr forKey:@"getaddress"];
            [dataDict setObject:phNumStr forKey:@"getphone"];
            // [dataDict setObject:nameStr forKey:@"getname"];

            [dataArray addObject:dataDict];

        }
        sqlite3_finalize(statement);
        sqlite3_close(_SQliteDB);

    }

}
return dataArray;

2 个答案:

答案 0 :(得分:1)

NSString *sqlQuery = [NSString 

    stringWithFormat:
                    @"SELECT ARTIST ,IMAGE FROM SONGS WHERE SONGNAME='kannulada'"]

;

kannulada是字符串,所以你必须使用单引号

答案 1 :(得分:-1)

问题是如果sqlite3_prepare_v2中有错误(它没有返回SQLITE_OK)。所以,如果发生这种情况,你应该看一下sqlite3_errmsg返回的内容,它会告诉你它为什么会失败。如果你没有看到SQLite返回的有意义的错误消息,那你就是盲目的。

if (sqlite3_prepare_v2(_SQliteDB, selectQuery, -1, &statement, NULL)== SQLITE_OK)
{
    ...
} else {
    NSLog(@"SQL Error: %s", sqlite3_errmsg(_SQliteDB));
}

关于它为什么失败,这是因为你必须引用字符串文字'kannulada',或者更好地使用SQL占位符?,然后使用sqlite3_bind_text。< / p>