1

SQLiteデータベースをiPadアプリに接続しました。ここで、データベースには2つのテーブルがあります。1つのテーブルはデータを入力し、他のテーブルはアプリで指定されたデータを保存します。しかし、問題は、データベースが更新されてデータが保存されていないことです。たとえば、テーブルに新しい名前を追加すると、自動的に入力されず、別の名前でdbファイルを再度追加した場合にのみ入力されます。保存したいデータを保存していません。

貴重なご提案をお願いします

参考までに私のコードを見つけてください:

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

@interface ViewController : UIViewController<UITextViewDelegate>{
    PersonDatabase *perDas;
    NSString * nameString;
    NSString * statusString;
      sqlite3 *database;
    NSString * empString;
}
@property (retain, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IBOutlet UIButton *signIn;
@property (strong, nonatomic) IBOutlet UIButton *signOut;
@property (strong, nonatomic) IBOutlet UILabel *nameLabel;
@property (strong, nonatomic) IBOutlet NSString * nameString;
@property (strong, nonatomic) IBOutlet NSString * statusString;

-(IBAction)signin:(id)sender;
-(IBAction)signout:(id)sender;
@end


#import "ViewController.h"
#import "PersonInfo.h"
#import "PersonDatabase.h"


@implementation ViewController
@synthesize tableView;
@synthesize signIn;
@synthesize signOut;
@synthesize nameLabel;
@synthesize  nameString,statusString;;

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (perDas == nil) {
        perDas = [[PersonDatabase alloc] init];
    }

    [tableView setDataSource:perDas];
    [tableView setDelegate:perDas];
    perDas.view = perDas.tableView;
}

-(IBAction)signin:(id)sender{
    NSLog(@"%@",perDas.string1);
    nameString=[[NSString alloc]initWithString:perDas.string1];
     statusString=[[NSString alloc]initWithFormat:@"IN"];
    {
        NSLog(@"passed");
        sqlite3_stmt    *statement;

        const char *dbpath = [perDas.databasePath UTF8String];

        if (sqlite3_open(dbpath, &database) == SQLITE_OK)
        {
            NSLog(@"pass");
            NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO status (names, staus, signin, singnout) VALUES (\"%@\", \"%@\", datetime(), \"%@\")", nameString, statusString,empString];
            NSLog(@"%@",insertSQL);
            const char *insert_stmt = [insertSQL UTF8String];

            int results= sqlite3_prepare_v2(database, insert_stmt, -1, &statement, NULL);
                NSLog(@"%i", results);
            if(sqlite3_step(statement) == SQLITE_DONE){
                NSLog(@"done");
            }else {
                printf( "could not prepare statemnt: %s\n", sqlite3_errmsg(database) );
            }
            sqlite3_finalize(statement);
            sqlite3_close(database);

    }
    }}
-(IBAction)signout:(id)sender{
 NSLog(@"%@",perDas.string1);}
- (void)viewDidUnload
{
    [self setTableView:nil];
    [self setSignIn:nil];
    [self setSignOut:nil];
    [self setNameLabel:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

@end


#import <Foundation/Foundation.h>

@interface PersonInfo : NSObject{
    int unique;
    NSString * nam;
}
@property(nonatomic, assign)int unique;
@property(nonatomic, copy)NSString * nam;
-(id) initWithUniqueId:(int)uniqueId name:(NSString *)name;
@end



#import "PersonInfo.h"

@implementation PersonInfo
@synthesize unique,nam;

-(id) initWithUniqueId:(int)uniqueId name:(NSString *)name{
    self=[super init];
    if (self) {
        self.unique=uniqueId;
        self.nam=name;

    }
    return self;
}

@end



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

@interface PersonDatabase : UITableViewController<UITableViewDataSource>{
    NSString *databaseName;
    NSString * databasePath;
    NSMutableArray *tableOne;
    NSString * string1;
    NSString * dateString;
    NSString * timeString;
     sqlite3 *database;
    NSString * empString;

}
@property(nonatomic, retain)  NSMutableArray  *tableOne;
@property(nonatomic, retain)  NSString * string1;
@property(nonatomic, retain)  NSString *  databasePath;

-(void)checkAndCreateDatabase;
-(void)readDataFromDatabase;

@end


#import "PersonDatabase.h"
#import "PersonInfo.h"
#import "ViewController.h"

@implementation PersonDatabase
@synthesize tableOne, string1,databasePath;

#pragma mark - View lifecycle
- (void)viewDidLoad
{

    databaseName=@"log.sqlite3";

    NSArray *documentPaths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * documentDir = [documentPaths objectAtIndex:0];
    databasePath=[documentDir stringByAppendingPathComponent:databaseName];
    [self checkAndCreateDatabase];
    [self readDataFromDatabase];
    [super viewDidLoad];
    NSLog(@"a");
    // Do any additional setup after loading the view, typically from a nib.
}

#pragma mark - TableView Data Source methods
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [tableOne count]; }

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell= nil;
    cell = [tableView dequeueReusableCellWithIdentifier:@"mycell"];
    if (cell == nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"mycell"];}

    PersonInfo * temp =(PersonInfo *)[self.tableOne objectAtIndex:indexPath.row];
    cell.textLabel.text=temp.nam;

    return cell;
}
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    string1 = cell.textLabel.text;
    NSLog(@"%@",string1);
}
-(void)checkAndCreateDatabase{
    BOOL success;
    NSFileManager *fileManager=[NSFileManager defaultManager];
    success=[fileManager fileExistsAtPath:databasePath];
    if(success)
        return;

    NSString *databasePathFromApp = [[[NSBundle mainBundle]resourcePath] stringByAppendingPathComponent:databaseName];
    [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}
-(void)readDataFromDatabase{
    tableOne=[[NSMutableArray alloc]init];
    if(sqlite3_open([databasePath UTF8String], &database)== SQLITE_OK){
        const char *sqlStatement = "SELECT * FROM names";
        sqlite3_stmt *compiledStatement;
        if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL)==SQLITE_OK){
            while (sqlite3_step(compiledStatement)==SQLITE_ROW) {
                int uniqueId = sqlite3_column_int(compiledStatement, 0);
                char *nameChars=(char *)sqlite3_column_text(compiledStatement,1);
                NSString *name=[[NSString alloc]initWithUTF8String:nameChars];
                PersonInfo *info=[[PersonInfo alloc]initWithUniqueId:uniqueId name:name];
                [tableOne addObject:info];
            }            
        }
        sqlite3_finalize(compiledStatement);
    }
    sqlite3_close(database);
}
@end

前もって感謝します!!!

4

1 に答える 1

0

以下は私のDB関数であり、正常に動作しています。これを試してください。

-(void)dbconnect{

    self.dbName=@"MyDb.sqlite";
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    self.dbPath=[documentsDir stringByAppendingPathComponent:self.dbName];
    NSLog(@"DBPATH%@",self.dbPath);
    [self checkAndCreateDatabase];
}
-(void)checkAndCreateDatabase{
    BOOL success;
    //check file exists in document directory
    NSFileManager *fileManager=[NSFileManager defaultManager];
    success=[fileManager fileExistsAtPath:self.dbPath];

    //if file exists in document directory then return

    if(success)
        return;

    //if file do not exists copy it in documents directory

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

    [fileManager copyItemAtPath:databasePathFromApp toPath:self.dbPath error:nil];
    [fileManager release];

}
-(sqlite3_stmt*) PrepareStatement:(const char *)sql{
    // Setup the database object
    sqlite3 *database;
    // Init the animals Array

    // Open the database from the users filessytem
    if(sqlite3_open([self.dbPath UTF8String], &database) == SQLITE_OK) {
        // Setup the SQL Statement and compile it for faster access
        const char *sqlStatement = sql;
        sqlite3_stmt *compiledStatement;

        if(sqlite3_prepare_v2(database, sqlStatement,-1, &compiledStatement, NULL) == SQLITE_OK) {
            //NSLog(@"COMPILED STATEMENT: %@",compiledStatement);
            return compiledStatement;

        }
    }
    return nil;
}
- (void) showException :(NSException *)e {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Trade Voice" message:[NSString stringWithFormat:@"Error - %@",e.name] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
    [alertView show];
    [alertView release];
}
/*DB CONN End*/
-(BOOL) sleepDatabase:(sqlite3 *)dbase {
    if (sqlite3_open([self.dbPath UTF8String], &dbase) == SQLITE_BUSY || sqlite3_open([self.dbPath UTF8String], &dbase) == SQLITE_LOCKED) {
        NSLog(@"Database in sleep");
        return YES;
    } else {
        return NO;
    }
}

//////更新を保存するコード削除

-(void)insertMaterialDetail:(Material *)objMaterial{
    sqlite3 *database;
    if(sqlite3_open([self.dbPath UTF8String], &database) == SQLITE_OK) {
        const char* sql = "INSERT INTO Material (name,amt) VALUES (?,?)";
        sqlite3_stmt *statement;
        statement = [self PrepareStatement:sql];

        int a1=sqlite3_bind_text(statement, 1, [objMaterial.name UTF8String], -1, SQLITE_TRANSIENT);
        int a2 = sqlite3_bind_double(statement, 2, objMaterial.amt);

        //NSLog(@"query %s",sql);
        if (statement)
        {
            if (a1 != SQLITE_OK || a2 != SQLITE_OK )
            {
                sqlite3_finalize(statement);
                return;
            }

            sqlite3_step(statement);
        }
        sqlite3_finalize(statement);
    }
}
-(int)updateMaterial:(Material *)objMaterial{

    @try {

        if(sqlite3_open([dbPath UTF8String], &delDatabase) == SQLITE_OK) {

            sqlite3_stmt* statement = nil;
            const char* sql = "update Material set name = ?, amt = ? where material_id = ?";



            statement = [self PrepareStatement:sql]; 

            int a1 = sqlite3_bind_text(statement, 1, [objMaterial.name UTF8String], -1, SQLITE_TRANSIENT);
            int a2 = sqlite3_bind_double(statement,2, objMaterial.amt);
            int a3 = sqlite3_bind_int(statement, 3, objMaterial.material_id);

            if (statement)
            {

                if (a1 != SQLITE_OK || a2 != SQLITE_OK || a3 != SQLITE_OK) 
                {
                    sqlite3_finalize(statement);
                    return 0;
                }

                sqlite3_step(statement);
            }
            sqlite3_finalize(statement);
        }
    }
    @catch (NSException * e) {
        [self showException:e];
    }
    @finally {
        sqlite3_close(delDatabase);
        return 1;
    }


}

-(void)deleteMaterial:(int)Materialid{
    sqlite3 *database;
    if(sqlite3_open([self.dbPath UTF8String], &database) == SQLITE_OK) {
        sqlite3_stmt *deleteStmt;
        const char *sql = "Delete from Material where material_id = ?";
        if(sqlite3_prepare_v2(database, sql, -1, &deleteStmt, NULL) != SQLITE_OK)
            NSAssert1(0, @"Error while creating delete statement. '%s'", sqlite3_errmsg(database));

        //When binding parameters, index starts from 1 and not zero.
        sqlite3_bind_int(deleteStmt, 1, Materialid);

        if (SQLITE_DONE != sqlite3_step(deleteStmt))
        {
            NSAssert1(0, @"Error while deleting. '%s'", sqlite3_errmsg(database));
        }
        sqlite3_reset(deleteStmt);
    }

}
于 2012-06-19T05:56:25.137 に答える