0

我目前有一个可以从中提取数据的表。我想做的是检查表是否已经存在于包中,如果不存在,我想创建表并将其保存到包中(意味着路径将在主包中)。我希望在 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 还是很陌生,所以如果我没有对我正在尝试做的事情提供足够准确的描述,请告诉我,我会尝试更具体。谢谢!

4

2 回答 2

5

快速搜索“iphone sql create table if not exists”给出最高结果。

这部分 SQL 可能就是您要查找的内容:

CREATE TABLE IF NOT EXISTS tableName( ... )

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

于 2012-05-07T15:39:55.737 回答
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)
    }
于 2019-06-01T07:24:24.967 回答