【问题标题】:List tables only show sqlite_sequence列表只显示 sqlite_sequence
【发布时间】:2012-12-10 09:06:57
【问题描述】:

我在模拟器中运行一个 iOS 程序,我收到了这个错误

'ISDatabaseSQLiteException',原因:'执行语句失败:'create table GroceryItem(primaryKey integer primary key autoincrement, name text NOT NULL, number integer NOT NULL)' with message: table GroceryItem already exists'

这是我在 AppDelegate.m 中使用的代码

self.database = [[[ISDatabase alloc] initWithFileName:@"db20121207.sqlite"] autorelease];

if(![[database tableNames] containsObject:@"GroceryItem"])
{        
    [database executeSql:@"create table GroceryItem(primaryKey integer primary key autoincrement, name text NOT NULL, number integer NOT NULL)"];    
    [database executeSql:@"insert into GroceryItem (name, number) values('apple', 5)"];    
    [database executeSql:@"insert into GroceryItem (name, number) values('zuoyou', 3)"];
}
else
{
    [database executeSql:@"insert into GroceryItem (name, number) values('apple', 5)"];
    [database executeSql:@"insert into GroceryItem (name, number) values('zuoyou', 3)"];
}

我有这个方法可以在sqlite_master 中列出表名

- (NSArray *) tables
{
    return [self executeSql:@"select * from sqlite_master where type = 'table'"];
}

- (NSArray *) tableNames
{
    NSLog(@"%@", [[self tables] valueForKey:@"name"]  );
    NSLog(@"%u", [[[self tables] valueForKey:@"name"] count]  );
    return [[self tables] valueForKey:@"name"];
}

但控制台显示

杂货清单[7439:c07] ( “sqlite_sequence” )

2012-12-10 16:59:40.305 GroceryList[7439:c07] 1

只得到表sqlite_sequence,计数为1;从上面的异常中,它说“表 GroceryItem 已经存在”

【问题讨论】:

    标签: ios sqlite


    【解决方案1】:

    我认为这个问题与executeSql 方法有关。

    从这段代码[[self tables] valueForKey:@"name"] 看来,您正在将表名添加到 NSDictionary 对象中。

    记住NSDictionary 中的所有键都是唯一的。您将使用 name 作为 key 将所有表名添加到字典中。

    所以它会覆盖之前添加的值。这就是它显示单个元素的原因。

    解决方案:

    1. 对不同的表名使用不同的键
    2. 使用NSMutableArray 代替NSDictionary
    3. 更改您的表格创建代码,如:

      [database executeSql:@"create table if not exists GroceryItem(primaryKey integer primary key autoincrement, name text NOT NULL, number integer NOT NULL)"];

    如果...其他条件则不需要那个

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-10
      • 2012-12-28
      • 1970-01-01
      相关资源
      最近更新 更多