1

创建数据库代码

这段代码是正确的。我使用该代码创建了一个数据库,它成功运行并创建了一个数据库,但我测试了我的应用程序,所以我删除或删除了我的模拟器应用程序并再次运行我的应用程序,然后我看到没有创建数据库。

请告诉我我面临的实际问题是什么。

ClsUpdateNetworkViewController.h

#import <UIKit/UIKit.h>
#import "Person.h"
#import <sqlite3.h>

@interface ClsUpdateNetworkViewController : UIViewController{

   UITextField *name;
   UITextField *phone;
   NSString *databasePath;
   sqlite3 *contactDB;
   int rowcount;

}

@property (nonatomic, strong) Person *person;
@property (nonatomic, strong) NSString *firstName;
@property (nonatomic, strong) NSString *lastName;
@property (nonatomic, strong) NSString *fullName;
@property (nonatomic, strong) NSString *phoneNumber;
@property (nonatomic, strong) NSString *workEmail;

@end

ClsUpdateNetworkViewController.m

 #import "ClsUpdateNetworkViewController.h"
 #import "ClsMainPageAppDelegate.h"
 #import "ClsAddressBookViewController.h"


@interface ClsUpdateNetworkViewController ()

@end

@implementation ClsUpdateNetworkViewController

@synthesize  person,firstName,lastName,fullName,phoneNumber,workEmail;
@synthesize name,phone;

- (void)viewDidLoad
{
   [super viewDidLoad];
// Do any additional setup after loading the view.

   [self createDatabase];
}



-(void) createDatabase
{
   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: @"contacts.db"]];

   NSFileManager *filemgr = [NSFileManager defaultManager];

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

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

           if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
           {
               NSLog(@"Failed to create table");

           }

           sqlite3_close(contactDB);

       }
       else
       {
           NSLog(@"Failed to open/create database");

       }
   }

}

我测试或调试我的应用程序

Code is not going inside this condition.
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
    // inside code is not executed.
}
4

3 回答 3

1

在didFinishLaunchingWithOptions调用此函数 :

-(void)createdb
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:@"emp.sqlite"];

NSURL *dbURL = [NSURL fileURLWithPath:dbPath];

// copy a database from the bundle if not present
// on disk
NSFileManager *fm = [NSFileManager defaultManager];
if (![fm fileExistsAtPath:dbPath])
{
    NSURL *bundlePath = [[NSBundle mainBundle] URLForResource:@"emp" withExtension:@"sqlite"];
    NSError *error = nil;
    if (!bundlePath || ![fm copyItemAtURL:bundlePath toURL:dbURL error:&error]) {
        NSLog(@"error copying database from bundle: %@", error);
    }
}
else
{
    NSLog(@"Success in Copy file");
}
}
于 2014-03-14T14:43:37.633 回答
0

它对我的工作方式是这样的

//-----------------------------------------------------------------------------------------------------//
#pragma mark - Shared Instance
//-----------------------------------------------------------------------------------------------------//


+ (SQLConnector *)database
{
    static SQLConnector *_sharedClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedClient = [[SQLConnector alloc]init];
    });
    return _sharedClient;
}



//-----------------------------------------------------------------------------------------------------//
#pragma mark - Initialization Methods
//-----------------------------------------------------------------------------------------------------//

- (id)init {
    if ((self = [super init]))
    {
        _databaseName = DB_NAME;

        NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDir = [documentPaths objectAtIndex:0];
        _databasePath = [documentsDir stringByAppendingPathComponent:_databaseName];
        NSLog(@"%@",_databasePath);

        if (sqlite3_open([[self dbPath] UTF8String], &_database) != SQLITE_OK)
        {
            [[[UIAlertView alloc]initWithTitle:@"Missing"
                                       message:@"Database file not found"
                                      delegate:nil
                             cancelButtonTitle:@"OK"
                             otherButtonTitles:nil, nil]show];
        }
    }
    return self;
}


- (NSString *)dbPath
{
    [self checkAndCreateDatabase];
    return _databasePath;
}


-(void) checkAndCreateDatabase
{
    // Check if the SQL database has already been saved to the users phone, if not then copy it over
    BOOL success;

    // Create a FileManager object, we will use this to check the status
    // of the database and to copy it over if required
    NSFileManager *fileManager = [NSFileManager defaultManager];

    // Check if the database has already been created in the users filesystem
    success = [fileManager fileExistsAtPath:_databasePath];

    // If the database already exists then return without doing anything
    if(success) return;

    // If not then proceed to copy the database from the application to the users filesystem

    // Get the path to the database in the application package
    NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:_databaseName];

    // Copy the database from the package to the users filesystem
    [fileManager copyItemAtPath:databasePathFromApp toPath:_databasePath error:nil];

}




//-----------------------------------------------------------------------------------------------------//
#pragma mark - Helper methods
//-----------------------------------------------------------------------------------------------------//

-(BOOL)dbOpenedSuccessfully
{
    if(sqlite3_open([[self dbPath] UTF8String], &_database) == SQLITE_OK)
    {
        return YES;
    }
    else
    {
        [[[UIAlertView alloc]initWithTitle:@"Error"
                                   message:@"Error on opening the DB"
                                  delegate:self
                         cancelButtonTitle:@"OK"
                         otherButtonTitles:nil, nil]show];
        return NO;
    }
}






//-----------------------------------------------------------------------------------------------------//
#pragma mark - Query
//-----------------------------------------------------------------------------------------------------//


- (void) executeQuery:(NSString *)strQuery
{
    char *error = NULL;
    if([self dbOpenedSuccessfully])
    {
        NSLog(@"%@",strQuery);
        sqlite3_exec(_database, [strQuery UTF8String], NULL, NULL,&error);
        if (error!=nil) {
            NSLog(@"%s",error);
        }
        sqlite3_close(_database);


    }

}
于 2013-07-19T09:19:25.813 回答
0

嗨,试试这个来创建数据库,只需将此代码添加到您的文件中

NSString *databaseName=@"Database.sqlite";

-(void)createDatabaseIfNeeded
{
    //  NSLog(@"Virtual database is created...");
        NSFileManager *fileManager=[[NSFileManager defaultManager]autorelease];
    NSError *error;
    NSArray *paths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path=[paths objectAtIndex:0];
    NSString *finalPath=[path stringByAppendingPathComponent:databaseName];
    //    NSLog(@"Database Path is:--> %@",finalPath);
    NSString *bundlePath=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];

    success = [fileManager fileExistsAtPath:finalPath];

    if(success)
    {
        if(sqlite3_open([finalPath UTF8String],&database)!=SQLITE_OK)
        {
            sqlite3_close(database);
        }
        return;
    }
    success=[fileManager copyItemAtPath:bundlePath toPath:finalPath error:&error];

    if(!success)
    {
        NSAssert1(0,@"Failed to create writable database file with message '%@' .",[error localizedDescription]);
    }
    else//First Time Loaded Application....
    {
        if(sqlite3_open([finalPath UTF8String],&database)!=SQLITE_OK)
        {
            sqlite3_close(database);
        }
    }
}
于 2013-07-19T09:04:02.790 回答