在iOS中创建sqlite数据库

时间:2013-01-02 12:29:21

标签: ios sqlite

如何获取在iOS中创建数据库的数据库路径? 我知道如何执行查询,但我想首先从文档目录创建数据库。

5 个答案:

答案 0 :(得分:0)

试试这个

-(void)copyDatabaseIfNeeded
{
    @try
    {
        NSFileManager *fmgr=[NSFileManager defaultManager];
        NSError *error;
        NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
        NSString *path=[paths objectAtIndex:0];
        dbPath=[path stringByAppendingPathComponent:@"Data.sqlite"];
        if(![fmgr fileExistsAtPath:dbPath]){
            NSString *defaultDBPath=[[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:@"Addict.sqlite"];
            if(![fmgr copyItemAtPath:defaultDBPath toPath:dbPath error:&error])
                NSLog(@"failure message----%@",[error localizedDescription]);
        }

    }
    @catch (NSException *exception)
    {
        NSLog(@"Exception: %@", exception);
    }

}

-(NSString *)getDBPath
{
    //Search for standard documents using NSSearchPathForDirectoriesInDomains
    //First Param = Searching the documents directory
    //Second Param = Searching the Users directory and not the System
    //Expand any tildes and identify home directories.
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];
    return [documentsDir stringByAppendingPathComponent:@"Data.sqlite"];
}

-(void)openDatabase
{
    [self copyDatabaseIfNeeded];

    if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
    {
        //Database Opened
        NSLog(@"Database opened");
    }
    else
    {
        NSLog(@"Database cannot be opened");
    }
}

-(void)closeDatabase
{
    sqlite3_close(database);
}

希望它可以帮助你..

答案 1 :(得分:0)

// Database handling
NSString *databaseFile = [[NSBundle mainBundle] pathForResource:@"DBname" ofType:@"sqlite"];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSString *dbPath = [basePath stringByAppendingPathComponent:[NSString stringWithFormat:@"DBname.sqlite"]];
NSFileManager *fm=[NSFileManager defaultManager];   
if(![fm fileExistsAtPath:dbPath]){
    [fm copyItemAtPath:databaseFile toPath:dbPath error:nil];
}

也许这会对你有所帮助

答案 2 :(得分:0)

试试这个:

// Get data
NSString *docsDir;
NSArray *dirPaths;

// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

docsDir = [dirPaths objectAtIndex:0];

// Build the path to the database file
databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:@"dbFileName.db"]];


NSFileManager *filemgr = [NSFileManager defaultManager];

if(![filemgr fileExistsAtPath:databasePath])
{
     NSData *content = [[NSData alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"dbFileName" ofType:@"db"] options:NSDataReadingMapped error:nil];
    [content writeToFile:databasePath options:NSDataWritingAtomic error:nil];
}

答案 3 :(得分:0)

是的我得到了答案谢谢你。 //这里可以帮助您从数据库中选择数据

-(NSMutableDictionary*)SelectAllData
{

   AppDelegate *AppDel=(AppDelegate *)[[UIApplication sharedApplication]delegate];
     [AppDel checkAndCreateDatabase];
    NSMutableArray *itemArray =[[[NSMutableArray alloc]init] autorelease];
    if(sqlite3_open([AppDel.databasePath UTF8String],&database) == SQLITE_OK)
        {
             NSString *sql =[NSString stringWithFormat:@"Select *from table"];

             sqlite3_stmt *selectstmt;

             if(sqlite3_prepare_v2(database, [sql UTF8String], -1, &selectstmt, NULL) == SQLITE_OK) 
                 {
                      while(sqlite3_step(selectstmt) == SQLITE_ROW) 
                          {
                               NSMutableDictionary *dicOfItem=[[NSMutableDictionary alloc]init];
                               [dicOfItem setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)] forKey:@"_id_article"];
                               [dicOfItem setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)] forKey:@"type"];
                               [dicOfItem setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)] forKey:@"Id"];


                               [itemArray addObject:dicOfItem];
                               [dicOfItem release];
                              }

                      sqlite3_close(database); 
                     }
            }

    else
         sqlite3_close(database); 
    //Even though the open call failed, close the database connection to release all the memory.
    NSMutableDictionary *dictresp = [NSMutableDictionary dictionaryWithObjectsAndKeys:itemArray,@"objects", nil];
    return dictresp;
}

//这可以帮助您从数据库中插入数据

- (void) insert_intable
{

    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate checkAndCreateDatabase];

    for(int i=0;i<[[articleDict objectForKey:@"objects"] count];i++)
    {

  if (sqlite3_open([[appDelegate databasePath] UTF8String], &database) == SQLITE_OK) {

        insertStmt=nil;
        if(insertStmt == nil) {
            NSString *sqlTmp=[NSString stringWithFormat:@"Insert into table(Type,Category_id) Values('%@','%@')",articleType,catID];

            const char *sqlStmt=[sqlTmp UTF8String];
            int returnValue = sqlite3_prepare_v2(database, sqlStmt, -1, &insertStmt, NULL);
            if (returnValue==SQLITE_OK) {
                  NSLog(@"Success");
            } else {   
                  NSLog(@"Unsuccess");
            }
             sqlite3_step(insertStmt);
             sqlite3_finalize(insertStmt);
            sqlite3_close(database);
        }
    }



    }        

}

答案 4 :(得分:0)

使用以下代码设置Sqlite路径

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
 databaseName=@"yourfileName.sqlite";
 NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *documentsDir = [documentPaths objectAtIndex:0];
 databasePath = [documentsDir stringByAppendingPathComponent:databaseName]; 
[self checkAndCreateDatabase]; 

}
-(void) checkAndCreateDatabase {

BOOL success;


NSFileManager *fileManager = [NSFileManager defaultManager];

success = [fileManager fileExistsAtPath:databasePath];

if(success) return;
else
    printf("NO File found");

NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];

[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];

}