在iOS中创建Sqlite数据库

在iOS中创建Sqlite数据库,ios,objective-c,sqlite,Ios,Objective C,Sqlite,我无法在文档目录中创建sqlite数据库。 代码如下: NSString *fileDir; NSArray *dirPaths; //Get the documents directory dirPaths = NSSearchPathForDirectoriesInDomains(NSDemoApplicationDirectory, NSUserDomainMask, YES); fileDir = [dirPaths objectAtIndex:0]; // Build

我无法在文档目录中创建sqlite数据库。 代码如下:

NSString *fileDir;
    NSArray *dirPaths;


//Get the documents directory

dirPaths = NSSearchPathForDirectoriesInDomains(NSDemoApplicationDirectory, NSUserDomainMask, YES);

fileDir = [dirPaths objectAtIndex:0];

// Build the database path
databasePath = [[NSString alloc]initWithString:[fileDir stringByAppendingPathComponent:@"student.sql"]];

NSFileManager *fileMgr = [NSFileManager defaultManager];

    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 CONTACTS(ID INTEGER PRIMARY KEY , NAME TEXT, ADDRESS TEXT, MOBILE INTEGER)";
            if (sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK) {
               _status.text = @"Failed to create table";                
            }
            sqlite3_close(database);

        }
        else
        {

            _status.text = @"Failed to open/create database";
        }
    }
我调试了代码,发现编译器没有在这种情况下运行。 sqlite3_open(dbPath和数据库)==SQLITE_OK

我不知道我做错了什么。 任何帮助都将不胜感激


谢谢,

检查您的代码以获得dirPath,您是否获得了正确的路径,我在代码中使用了以下方法,它对我有效:

dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// dirPaths = NSSearchPathForDirectoriesInDomains(NSDemoApplicationDirectory, NSUserDomainMask,YES);
  fileDir = dirPaths[0];

// Build the database path
databasePath = [[NSString alloc]initWithString:[fileDir stringByAppendingPathComponent:@"student.sqlite"]];

我就是这样做的

数据库访问

static sqlite3 *database=nil;

-(id)init
{
if(self=[super init])
{
    self.user_data=@"user_data.db";
}
return self;
}


-(void)createUserDataDatabase
{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:user_data];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;

// construct database from external ud.sql

NSString *filePath=[[NSBundle mainBundle]pathForResource:@"ud" ofType:@"sql"];
NSString *sqlStatement=[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
if(sqlite3_open([writableDBPath UTF8String], &database)==SQLITE_OK)
{
    sqlite3_exec(database, [sqlStatement UTF8String], NULL, NULL, NULL);
    sqlite3_close(database);
}
}
外部sql文件必须包含以下sql查询:

CREATE TABLE quantityInSubCountries ( 
refID    INT,
quantity INT 
);

CREATE TABLE quantityInSubRegions ( 
refID    INT,
quantity INT 
); ....

希望对您有所帮助。

这是数据库常用的方法

    -(void)updateTable:(NSString *)tableName setname:(NSString *)Name setImagePath:(NSString *)imagePath whereID:(NSInteger)rid{

        NSString *sqlString=[NSString stringWithFormat:@"update %@ set name='%@' where id=%ld",tableName,Name,rid];

        char *error;
        if (sqlite3_exec(db, [sqlString UTF8String], NULL, NULL, &error)!=SQLITE_OK) {
            [self closeDatabase];
            NSLog(@"Faield to update");
        }
        else{

            NSLog(@"update successfully");
        }
    }

    -(void)deleteFrom:(NSString *)tablename whereName:(NSInteger )rid {
       NSString *sqlString=[NSString stringWithFormat:@"delete from %@ where id=%ld",tablename,(long)rid];

        char *error;
        if (sqlite3_exec(db, [sqlString UTF8String], NULL, NULL, &error)!=SQLITE_OK) {
            [self closeDatabase];
            NSLog(@"faield to Delete");
        }
        else{

            NSLog(@"Deleted successfully");
        }
    }

    -(void)insertInTable:(NSString *)tableName withName:(NSString *)name withImagePath:(NSString *)imagePath
    {


        NSString *sqlString=[NSString stringWithFormat:@"insert into %@(name,path)values('%@','%@')",tableName,name,imagePath];
        char *error;
        if (sqlite3_exec(db, [sqlString UTF8String], NULL, NULL, &error)!=SQLITE_OK) {
            [self closeDatabase];
            NSLog(@"Failed to insert");

        }
        else{
            NSLog(@"Inserted succesfully");

        }

    }

    -(NSString *)path
    {
        NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentDir=[paths objectAtIndex:0];
        return [documentDir stringByAppendingPathComponent:@"Storage.db"];

    }
    -(void)open{
        if(sqlite3_open([[self path] UTF8String], &db)!=SQLITE_OK)
        {
            sqlite3_close(db);
            NSLog(@"your database table has been crash");
        }
        else{
            NSLog(@"Database open successfully");
        }

    }
    -(void)closeDatabase
    {
        sqlite3_close(db);
        NSLog(@"Database closed");
    }

    -(void)copyFileToDocumentPath:(NSString *)fileName withExtension:(NSString *)ext{
        NSString *filePath=[self path];
        NSFileManager *fileManager=[NSFileManager defaultManager];
        if (![fileManager fileExistsAtPath:filePath]) {
            NSString *pathToFileInBundle=[[NSBundle mainBundle] pathForResource:fileName ofType:ext];
            NSError *err=nil;
            BOOL suc=[fileManager copyItemAtPath:pathToFileInBundle toPath:filePath error:&err];
            if (suc) {
                NSLog(@"file copied successfully");
            }
            else
            {
                NSLog(@"faield to copied");
            }
        }
        else
        {
            NSLog(@"File allready present");
        }

    }


    -(NSMutableArray *)AllRowFromTableName:(NSString *)tableName{
        NSMutableArray *array=[[NSMutableArray alloc] init];
        NSString *sqlString=[NSString stringWithFormat:@"select *from %@",tableName];
        sqlite3_stmt *statement;
        if (sqlite3_prepare_v2(db, [sqlString UTF8String], -1, &statement, nil)==SQLITE_OK) {
            while (sqlite3_step(statement)==SQLITE_ROW) {
              Database *tempDatabase=[[Database alloc] init];
              tempDatabase.Hid=sqlite3_column_int(statement, 0);
              tempDatabase.Hname =[[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
              tempDatabase.Hpath=[[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
              [array addObject:tempDatabase];
            }
        }
        return array;
    }

-(void)test
{

//Pet photos
    NSString *sqlString=[NSString stringWithFormat:@"create table if not exists StorageTable(id integer primary key autoincrement,name text,path text)"];

    char *error;
    if (sqlite3_exec(db, [sqlString UTF8String], NULL, NULL, &error)!=SQLITE_OK) {
        [self closeDatabase];
        NSLog(@"Faield to blanck 1 %s",error);
    }
    else{
        NSLog(@"Test On StorageTable Database successfully");
    }
}

嗯,sqlite3_open返回的返回码是什么?sqlite3_errmsg报告了什么?(顺便说一句,假设您真的在“调试”以找出失败的地方,编译器没有参与。)我认为您必须更改文件扩展名,即student.sqlite。只需打印出您试图打开的路径,并确保它存在。(我从未见过使用NSDemoApplicationDirectory。)