Objective-c sql错误 - 语句错误看起来像空结果

时间:2013-08-14 10:43:08

标签: ios sql objective-c database sqlite

嗨,我遇到了一些代码。我有一个文件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] ()

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

4 个答案:

答案 0 :(得分:1)

下面

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

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

答案 1 :(得分:1)

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)然后以这种方式与数据库交谈。

- (无效)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);

}

答案 2 :(得分:0)

尝试这样,在进入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. 
                }
            }
         } 

答案 3 :(得分:0)

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

我想我发现了导致它的原因。

我改变了我的查询:

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

这种方式有效...所以看起来我在阅读其他表时遇到了麻烦...... 我添加另一张桌子的那一刻它停止了工作。但这是外部数据库管理器软件的奇怪原因,查询工作正常