SQLite,将数据从不同的视图插入到数据库中

时间:2012-11-05 16:55:01

标签: ios database xcode sqlite insert

我们在默认的ViewController.m中声明了以下代码:

-(void)saveData{
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];

if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
    NSString *insertSQL = [NSString stringWithFormat:
                           @"INSERT INTO CONTACTS (name, address, phone) VALUES (\"%@\", \"%@\", \"%@\")",
                           name.text, address.text, phone.text];
    const char *insert_stmt = [insertSQL UTF8String];
    sqlite3_prepare_v2(contactDB, insert_stmt,-1, &statement, NULL);
    if (sqlite3_step(statement) == SQLITE_DONE)
    {
        name.text = @"";
        address.text = @"";
        phone.text = @"";
    sqlite3_finalize(statement);
    sqlite3_close(contactDB);
    }
}

}

- (无效)findContact {

const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;

if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
    NSString *querySQL = [NSString stringWithFormat:@"SELECT address, phone FROM contacts WHERE name=\"%@\"", name.text];
    const char *query_stmt = [querySQL UTF8String];

    if (sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
    {
        if (sqlite3_step(statement) == SQLITE_ROW)
        {
            NSString *addressField = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
            address.text = addressField;
            NSString *phoneField = [[NSString alloc]
                                    initWithUTF8String:(const char *)
                                    sqlite3_column_text(statement, 1)];
            phone.text = phoneField;

            status.text = @"Match found";
        } else {
            status.text = @"Match not found";
            address.text = @"";
            phone.text = @"";

        }
        sqlite3_finalize(statement);
    }
    sqlite3_close(contactDB);
}

}

- (无效)viewDidLoad中{

[super viewDidLoad];
NSString *docsDir;
NSArray *dirPaths;
dirPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir=[dirPaths objectAtIndex:0];
databasePath=[[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:@"contacts.db"]];
NSFileManager *filemgr=[NSFileManager defaultManager];
if([filemgr fileExistsAtPath:databasePath]==NO)
{
    const char *dbpath=[databasePath UTF8String];
    if(sqlite3_open(dbpath, &contactDB)==SQLITE_OK)
    {
        char *errMsg;
        const char *sql_stmt =
        "CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)";

        if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
        {
            status.text = @"Failed to create table";
        }
        sqlite3_close(contactDB);
    } else {
        status.text = @"Failed to open/create database";
    }
}

}

它可以工作,但我们希望从不同的viewControllerName.m访问该数据库(contactDB);我们尝试过以下方法:

// Scene2ViewController.m

- (void)incrementoBarra {

if(barra.progress == 1){

   //In this method we want to insert the address data into the specified name. 

   sqlite3_stmt *statement;
   const char *dbpath = [databasePath UTF8String];

   if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
   {
       NSString *insertSQL = [NSString stringWithFormat:
                              @"INSERT INTO CONTACTS (name, address) VALUES (\"%@\", \"%d\")",
                              usuario, tiempo];
       const char *insert_stmt = [insertSQL UTF8String];
       sqlite3_prepare_v2(contactDB, insert_stmt,-1, &statement, NULL);
       if (sqlite3_step(statement) == SQLITE_DONE)
       {
           sqlite3_finalize(statement);
           sqlite3_close(contactDB);
       }
   }

   //


   [self performSelector:@selector(hideImage) withObject: nil afterDelay:1.0];


}

}

由于变量和数据库出错而导致无法正常工作

我们如何实现这些变量和数据库以便从不同的.m中使用它们? 谢谢你的时间!

1 个答案:

答案 0 :(得分:0)

我认为这个问题有很多答案,所以我只会解释一下我想要解决的问题,然后尝试解释原因。好了!

由于你有类似的逻辑要在不同的位置使用(在这种情况下是多个文件),我会将这个逻辑移动到一个新类(.h和.m文件用于实现)。考虑到与数据库交互的逻辑,我会继续将其命名为“DatabaseManager”。现在,该类可以让您访问所需的逻辑。

为确保您始终能够访问DatabaseManager,将其设为Singleton可能是明智之举(请参阅http://en.m.wikipedia.org/wiki/Singleton_pattern)。