检查表是否存在以及它是否不存在,创建它... iOS / SQLite

时间:2012-05-07 15:13:01

标签: ios sqlite

我目前有一个存在的表,我可以从中提取数据。我想要做的是检查表中是否已经存在表,如果没有,我想创建表并将其保存到bundle(意味着路径将在主包中)。我希望在setInput方法的顶部检查和创建数据库。我一直在寻找与此类似的东西,但我还没有想出任何东西。非常感谢任何帮助。这是我的代码:

-(IBAction)setInput:(id)sender
{
    NSString *strStoreNumber;
    NSString *strRegNumber;

    strStoreNumber = StoreNumber.text;
    strRegNumber = RegNumber.text;
    lblStoreNumber.text = strStoreNumber;
    lblRegNumber.text = strRegNumber;

    NSString* databasePath = [[NSBundle mainBundle] pathForResource:@"tblStore" ofType:@"sqlite"];

    if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) 
    {
        NSLog(@"Opened sqlite database at %@", databasePath);
        sqlite3_exec(database, "CREATE TABLE IF NOT EXISTS tblStore (ID INTEGER PRIMARY KEY AUTOINCREMENT, Message TEXT)", NULL, NULL, NULL);
        //...stuff
    } 
    else 
    {
        NSLog(@"Failed to open database at %@ with error %s", databasePath, sqlite3_errmsg(database));
        sqlite3_close (database);
    }
//    
    NSString *querystring;

    // create your statement
    querystring = [NSString stringWithFormat:@"SELECT strStore, strReg FROM tblStore WHERE strStore = %@ AND strReg = %@;", strStoreNumber, strRegNumber];  

    const char *sql = [querystring UTF8String];

    NSString *szStore = nil;
    NSString *szReg = nil;

    sqlite3_stmt *statement = nil;
    if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL)!=SQLITE_OK) //queryString = Statement
    {
        NSLog(@"sql problem occured with: %s", sql);
        NSLog(@"%s", sqlite3_errmsg(database));
    }
    else
    {
        // you could handle multiple rows here
        while (sqlite3_step(statement) == SQLITE_ROW) 
        {            
            szStore = [NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 0)];
            szReg = [NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 1)];
        }        

    }

    sqlite3_finalize(statement);

    lblStoreNumber.text = szStore;
    lblRegNumber.text = szReg;

//   
} 

我还是iOS和SQLite的新手,所以如果我没有准确描述我正在尝试做什么,请告诉我,我会尝试更具体。谢谢!

2 个答案:

答案 0 :(得分:5)

快速搜索“iphone sql create table if not exists”将this作为最佳结果。

这部分SQL可能就是你要找的东西:

CREATE TABLE IF NOT EXISTS tableName( ... )

如果表尚不存在,它会创建一个表。

答案 1 :(得分:0)

使用sqlite swift创建表

func createTable(_ tableName:String) {
        sqlStatement = "CREATE TABLE \(tableName)(Id TEXT,Details BLOB,Type TEXT)"
        if sqlite3_prepare_v2(database, sqlStatement,-1, &compiledStatement, nil) == SQLITE_OK {
            if sqlite3_step(compiledStatement) == SQLITE_DONE {
                print("table created")
            }
            else {
                print("table could not be created")
            }
        }
        else {
            print("Create table statement could not be prepared")
        }
        sqlite3_finalize(compiledStatement)
    }