如何以编程方式在SQLite中创建多个表,即;通过ios中的代码

时间:2013-12-02 12:34:53

标签: ios sqlite

if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
    const char *dbpath = [databasePath UTF8String];

    if (sqlite3_open(dbpath, &_taxOrganizerDB) == SQLITE_OK)
    {
      char *errMsg;
      const char *sql_stmt = "CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, ADDRESS TEXT,PHONE NO INT)";

      if (sqlite3_exec(_taxOrganizerDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
      {

      }

      sqlite3_close(_taxOrganizerDB);

    } else 
    {
    }
}

我想在sqlite浏览器中创建多个表,用于单个应用程序。

2 个答案:

答案 0 :(得分:2)

只需在字符串上添加多个语句

    if ([filemgr fileExistsAtPath: _databasePath ] == NO)
    {
        const char *dbpath = [_databasePath UTF8String];
        if (sqlite3_open(dbpath, &_database) == SQLITE_OK)
        {
            char *errMsg;
            const char *sql_stmt =
            "CREATE TABLE IF NOT EXISTS TEST (ID INTEGER PRIMARY KEY AUTOINCREMENT, DATA TEXT);" //TEST
            "CREATE TABLE IF NOT EXISTS USER (USER_ID INTEGER PRIMARY KEY AUTOINCREMENT, PASSWORD TEXT, TYPE TEXT);" //USER
            "CREATE TABLE IF NOT EXISTS METADATA (METADATA_ID INTEGER PRIMARY KEY AUTOINCREMENT, VERSION TEXT)"; //METADATA


            if (sqlite3_exec(_database, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
            {
                NSLog(@"Failed to create tables");
            }
            sqlite3_close(_database);
            NSLog(@"DataBase created at: %@",_databasePath);
        } else {
            NSLog(@"Failed to open/create database");
        }
    }

答案 1 :(得分:0)

您的create table语句是创建表的方法,但是列名不能包含空格。将您的“电话号码”更改为“Phone_No”,它应该可以正常工作。此外,您不需要自动增量。声明为整数主键的任何列都将自动自动增量。