检查SQLite3数据库是否包含任何数据

时间:2015-05-21 13:31:38

标签: ios sqlite

将SQLITE3数据库设置为应用程序中的永久存储。我需要检查是否存在填充了表的数据库对象,并且如果没有表存在则执行SQL DDL语句(即在首次启动APP时),想知道接下来的最佳方法是我下面的内容还是完全错误/有没有更好的办法?!我可以在int ri = sqlite3_open_v2(" schoolDatabase.db",& _database,SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,NULL)之后检查数据库属性为null / nil;命令或即使数据库没有表,它会返回一个值吗?

@interface DBAccess ()
@property (nonatomic,strong) sqlite3 *database;

@implementation DBAccess
@synthesize database = _database

-(id)init

int check =sqlite3_initialise();
if(check==SQLITE_OK){
int ri = sqlite3_open_v2("schoolDatabase.db",&_database,  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,NULL);
if(ri==SQLITE_OK){ 
NSLOG(@"Database created successfully}; 
else{ NSLog(@"problem creating database");}

sqlite3_stmt *statement;
const char *databaseExistence = "SELECT name FROM sqlite_master WHERE Type = table";
sqlite3_prepare_v2(self.database,databseExistence,-1,&statement,NULL);

while(sqlite3_step(statement)==SQLITE_ROW)
{
  //I am presuming column indexes are zero based in sqlite3 ?
  const unsigned char *tableNames = sqlite3_column_text(statement,2);
if(tableNames=nil){
NSLog(@"Tables in database do not exist......creating tables"
//insert SQL statement to prepare and execute CREATE TABLE commands for the Blank database   

1 个答案:

答案 0 :(得分:1)

您可以查看application_id和/或user_version个pragma。

如果它们为零,那么您已经打开了一个新数据库,并且可以设置您的架构(并将它们设置为您自己的幻数)。如果它们匹配您的幻数,那么数据库就存在了。如果他们不是非零但不匹配,那么有人会更改它们,您可能会提前出错。

相关问题