【问题标题】:Objective-c sql error - error with statement look like empty resultObjective-c sql错误-语句错误看起来像空结果
【发布时间】:2013-08-14 10:43:08
【问题描述】:

嗨,我遇到了一些代码。我有一个文件 catalog.db 和一个让我使用它的类。当我尝试从数据库中检索数据时,它似乎是空的。通过几个 nslog,我可以看到它连接并进入数据库,我可以看到它进入其中,但它不会从中获得任何价值。 我试图查看外部数据库管理器软件的查询是否有问题,并且查询工作正常......

这是我的课

#import "DBAccess.h"
sqlite3* database;

@implementation DBAccess


-(id)init{
    self = [super init];
    if (self){       
        [self initializeDatabase];
    }
    return self;
}


-(void)initializeDatabase{
    NSString *path = [[NSBundle mainBundle]pathForResource:@"catalog" ofType:@"db"];
    if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) { NSLog(@"Opening Database"); }
    else {
        sqlite3_close(database);
        NSAssert1(0, @"FAILED to open database '%s'", sqlite3_errmsg(database));
    }
}



-(void)closeDatabase{
    if (sqlite3_close(database) != SQLITE_OK){
        NSAssert1(0, @"ERROR to close databse: '%s'", sqlite3_errmsg(database));
    }
}



-(NSMutableArray *)getAllProduct{

    NSMutableArray *products = [[NSMutableArray alloc]init];
    const char *sql = "SELECT product.ID,product.Name, Manufacturer.name, product.details,product.price, product.quantityOnHand,country.country,product.image FROM product,manufacturer,country WHERE manufacturer.manufacturerID = product.manufacturerID and product.countryOfOriginID = country.countryID";

    sqlite3_stmt *statement;

 int sqlResult = sqlite3_prepare_v2(database, sql, -1, &statement, NULL);
 NSLog(@"sqlResult: %d", sqlResult);
 if (sqlResult == SQLITE_OK){
    NSLog(@"sql step statement: %d",sqlite3_step(statement));
    NSLog(@"QUERY DONE");

    while (sqlite3_step(statement) == SQLITE_ROW){

        NSLog(@"TEST");

        Product *product = [[Product alloc]init];

        char *name = (char *)sqlite3_column_text(statement, 1);
        NSLog(@"n %s",name);
        char *manufacturer = (char *)sqlite3_column_text(statement, 2);
        NSLog(@"m %s", manufacturer);
        char *details = (char *)sqlite3_column_text(statement, 3);
        NSLog(@"d %s", details);
        char *countryoforigin = (char *)sqlite3_column_text(statement, 6);
        NSLog(@"%s", countryoforigin);
        char *image = (char *)sqlite3_column_text(statement, 7);
        NSLog(@"%s", image);

        product.ID = sqlite3_column_text(statement, 0);
        product.name = (name)?[NSString stringWithUTF8String:name]:@"";
        product.manufacturer = (manufacturer)?[NSString stringWithUTF8String:manufacturer]:@"";
        product.details = (details)?[NSString stringWithUTF8String:details]:@"";
        product.price = sqlite3_column_double (statement, 4);
        product.quantity = sqlite3_column_int(statement, 5);
        product.countryOfOrigin = (countryoforigin)?[NSString stringWithUTF8String:countryoforigin]:@"";
        product.image = (image)?[NSString stringWithUTF8String:image]:@"";
        [products addObject:product];
    }
    sqlite3_finalize(statement);
}
else {
    NSLog(@"Problem with database %d",sqlResult);
}
return products;
}

@end

这是我在控制台中得到的

2013-08-14 12:38:58.505 Catalog[1642:c07] Opening Database
2013-08-14 12:38:58.508 Catalog[1642:c07] sqlResult: 0
2013-08-14 12:38:58.509 Catalog[1642:c07] sql step statement: 101
2013-08-14 12:38:58.509 Catalog[1642:c07] QUERY DONE
2013-08-14 12:38:58.510 Catalog[1642:c07] ()

我的问题可能是什么?谢谢

【问题讨论】:

    标签: ios sql objective-c database sqlite


    【解决方案1】:

    这里

    NSLog(@"sql step statement: %d",sqlite3_step(statement));
    

    您已经获取了第一行(不使用结果)。

    【讨论】:

    • 我添加它只是作为测试...即使删除它也行不通...同样的错误,同样的结果
    • @Mario:那我不知道。但是返回值101是SQLITE_DONE,表示没有匹配的行。
    • 怎么可能?如果我使用外部 DbManager 软件执行相同的语句,我会毫无问题地得到结果
    • @Mario:对不起,我不知道。
    【解决方案2】:

    1)将数据库复制到您的文档目录...

    -(void) checkAndCreateDatabase{ // 检查SQL数据库是否已经保存到用户手机,如果没有则复制过来

    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    NSString *databasePath = [documentsDir stringByAppendingPathComponent:@"test.sqlite"];
    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:@"test.sqlite"];
    
    // Copy the database from the package to the users filesystem
    [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
    

    }

    2)然后以这种方式与数据库对话。

    -(void)sqliteTransaction { sqlite3 *数据库;

    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    NSString *databasePath = [documentsDir stringByAppendingPathComponent:@"test.sqlite"];
    
    // Init the animals Array
    
    
    // Open the database from the users filessytem
    if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
        // Setup the SQL Statement and compile it for faster access
        const char *sqlStatement = "select * from me";
        sqlite3_stmt *compiledStatement;
        if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
            // Loop through the results and add them to the feeds array
            while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
                // Read the data from the result row
                NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
    
    
                NSLog(@"%@",aName);
                // Create a new animal object with the data from the database
    
            }
        }
        // Release the compiled statement from memory
        sqlite3_finalize(compiledStatement);
    
    }
    sqlite3_close(database);
    

    }

    【讨论】:

      【解决方案3】:

      尝试这样,在进行 SELECT 之前,确保表已正确连接以使用这样的打开查询进行选择

      sqlite3_open(dbpath, &ProDB)

      然后执行您的选择。请参阅下面的示例代码。希望它会有所帮助 例如:

       NSMutableArray *sessionDetails = [NSMutableArray array];
      
      NSString *docsDir;
          NSArray *dirPaths;
      
          dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
      
          docsDir = [dirPaths objectAtIndex:0];
      
          NSString *databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"cPro.db"]];
      
      
      
              const char *dbpath = [databasePath UTF8String];
              sqlite3_stmt *statement;
      
              if (sqlite3_open(dbpath, &ProDB) == SQLITE_OK)
              {
      
                  NSString *querySQL = [NSString stringWithFormat: @"SELECT * FROM USER_SESSION_INFO"];
                  NSLog(@"query: %@",querySQL);
                  const char *query_stmt = [querySQL UTF8String];
      
                  if (sqlite3_prepare_v2(ProDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
                  {
                      while(sqlite3_step(statement) == SQLITE_ROW)
                      {
                          // Your functionality. 
                      }
                  }
               } 
      

      【讨论】:

        【解决方案4】:

        我尝试了你们建议的方法,但我仍然遇到同样的问题。

        我想我找到了它的原因。

        我用这个改变了我的查询:

         const char *sql = "SELECT product.ID,product.Name, product.details,product.price, product.quantityOnHand,product.image FROM Product";
        

        这样就可以了...所以看起来我在阅读其他表格时遇到了麻烦... 当我添加另一个表时,它停止工作。但这很奇怪,因为外部数据库管理器软件查询工作正常

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-12-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-08-17
          • 2021-03-22
          相关资源
          最近更新 更多