How to create table in sqlite data base programmatically in iPhone

How to create table in sqlite data base programmatically in iPhone


The database that can be used by apps in iOS (and also used by iOS) is called SQLite, and it’s a relational database. It is contained in a C-library that is embedded to the app that is about to use it. Note that it does not consist of a separate service or daemon running on the background and attached to the app. On the contrary, the app runs it as an integral part of it. Nowadays, SQLite lives its third version, so it’s also commonly referred as SQLite 3.

SQLite isn’t the only way to persist data on iOS. Besides Core Data, there are lots of other alternatives for data persistence, including Realm, Couchbase Lite, Firebase, and NSCoding.

SQLite is not as powerful as other DMBSs, such as MySQL or SQL Server, as it does not include all of their features. However, its greatness lies mostly to these factors:

  • It’s lightweight.
  • It contains an embedded SQL engine, so almost all of your SQL knowledge can be applied.
  • It works as part of the app itself, and it doesn’t require extra active services.
  • It’s very reliable.
  • It’s fast.
  • It’s fully supported by Apple, as it’s used in both iOS and Mac OS.
  • It has continuous support by developers in the whole world and new features are always added to it.

Creating a Table
Now that you have a connection to a database file, you can create a table. You’ll work with a very simple table to store contacts.



if (sqlite3_open(dbpath, &myDB) == SQLITE_OK) {

        NSString *charsTableNameQuery = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@(id INTEGER PRIMARY KEY, charName TEXT)",charsTableName];

        int results = 0;

        //create all chars tables
        const char *charsTableNameQuerySQL = [charsTableNameQuery UTF8String];
        sqlite3_stmt * charsTableNameStatment = nil;
        results = sqlite3_exec(myDB, charsTableNameQuerySQL, NULL, NULL, NULL);
        if (results != SQLITE_DONE) {
            const char *err = sqlite3_errmsg(tekkenDB);
            NSString *errMsg = [NSString stringWithFormat:@"%s",err];
            if (![errMsg isEqualToString:@"not an error"]) {
                NSLog(@"createTables-chartables error: %@",errMsg);
                return FALSE;




func createTable() {
// 1
var createTableStatement: OpaquePointer? = nil
// 2
if sqlite3_prepare_v2(db, createTableString, -1, &createTableStatement, nil) == SQLITE_OK {
// 3
if sqlite3_step(createTableStatement) == SQLITE_DONE {
print("Contact table created.")
} else {
print("Contact table could not be created.")
} else {
print("CREATE TABLE statement could not be prepared.")
// 4