-1

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

4 回答 4

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

-(void)sqliteTransaction { sqlite3 *database;

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);

}

于 2013-08-14T12:02:41.707 回答
1

这里

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

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

于 2013-08-14T10:49:20.087 回答
0

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

我想我发现是什么原因造成的。

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

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

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

于 2013-08-14T18:16:47.323 回答
0

Try like this, before going to SELECT make sure the table is properly connected for selection with the open query like this

sqlite3_open(dbpath, &ProDB)

After that execute your selection. See this below sample code. Hope it will help ex:

 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. 
                }
            }
         } 
于 2013-08-14T11:40:29.547 回答