Значения вставлены в симулятор, но не отображаются в таблице базы данных - PullRequest
1 голос
/ 18 апреля 2011

Я создал оператор insert для моей базы данных SQLite, который вставляет записи. Мой код работает правильно - когда я запускаю свой код, он показывает сообщение о добавлении новой записи. Когда я открываю SQLite Browser, чтобы увидеть, была ли запись добавлена ​​в таблицу базы данных, запись не появляется. В чем может быть проблема? Мой код работает правильно. Показывает сообщение о добавлении контакта в симуляторе, но в базе данных контакт не добавляется. Пожалуйста, помогите мне в решении этой проблемы.

Это мой код:

#import <UIKit/UIKit.h>
#import "TAddNewJourney.h"

@interface insertAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
    TAddNewJourney *iC;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) TAddNewJourney *iC;

-(void) chekAndCreateDatabase;
-(void)insert;
@end

.m файл:

#import "insertAppDelegate.h"
#import <sqlite3.h>
#import "TAddNewJourney.h"

#import "Global.h"

@implementation insertAppDelegate

@synthesize window;
@synthesize iC;

static NSString* databaseName;
static NSString* databasePath;
static sqlite3* database;





  -(void) chekAndCreateDatabase
{
    BOOL success;
    databaseName=@"demo.sqlite";
    NSArray *documentPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir =[documentPaths objectAtIndex:0];
    databasePath      = [NSString stringWithFormat:@"%@/%@", documentsDir, databaseName];
    NSLog(@"Database Path is: %@", databasePath);
    NSLog(@"Database Name is: %@", databaseName);

    NSFileManager *fileManager=[NSFileManager defaultManager];
    if( [fileManager fileExistsAtPath:databasePath] == NO ) {
        // Open database.
        if( sqlite3_open( [databasePath UTF8String], &database ) == SQLITE_OK ) {
            char* errorMsg;
            // Create Articles Table.
            const char* articlesTable = "CREATE TABLE [UserJourney] (name text, location text)";
            if( sqlite3_exec(database, articlesTable, NULL, NULL, &errorMsg) != SQLITE_OK )
                NSLog( @"Fail to create UserJourney table. Error is: %@", errorMsg );


        } else NSLog(@"Fail to Create/Open database");
    }
    else {
        NSLog(@"Open database.");
        sqlite3_open( [databasePath UTF8String], &database );
    }
}



-(void)insert{
    [self chekAndCreateDatabase];

// Create Pre Sqlite query string.
NSString* preSqliteQuery = @"INSERT INTO UserJourney  VALUES ('%@', '%@')";

// Create Sqlite query string.
NSString* queryString = [NSString stringWithFormat:preSqliteQuery,Gjourney,Glocation];
// Execute query.
if(sqlite3_exec(database, [queryString UTF8String], NULL, NULL, NULL)== SQLITE_DONE){

    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"UIAlertView" message:@"Record added" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [alert release];
    alert = nil;
}
else {
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"UIAlertView" message:@"not Added" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [alert release]; 
    alert = nil;
}

Это мой класс контроллера:

@interface TAddNewJourney : UIViewController {

    IBOutlet UITextField *mTextJourney;
    IBOutlet UITextField *mTextLocation;
        IBOutlet UIButton *mStart;
    IBOutlet UIButton *mCancel;

}

@property (nonatomic,retain)UITextField *textjourney;
@property (nonatomic,retain)UITextField *textlocation;

-(IBAction)Start:(id)sender;
-(IBAction)Cancel:(id)sender;

@end

.m файл

#import "TAddNewJourney.h"
#import "Global.h"
#import <sqlite3.h>
#import "insertAppDelegate.h"


@implementation TAddNewJourney
@synthesize textjourney=mTextJourney;
@synthesize textlocation =mTextLocation;

-(IBAction)Start:(id)sender{
    Gjourney = mTextJourney.text;
    Glocation = mTextLocation.text;

       insertAppDelegate *app=(insertAppDelegate *)[[UIApplication sharedApplication]delegate];
    [app insert];

}

Ответы [ 3 ]

0 голосов
/ 19 апреля 2011

.h файл

#import <Foundation/Foundation.h>
#import <sqlite3.h>

@interface SqliteDatabase : NSObject {


}

// Check and Create Sqlite Table.
+ (void) CheckAndCreateDatabase;
+ (void) insert;

@end

.m файл

// Static Variables.
static NSString* dataBaseName;
static NSString* dataBasePath;
static sqlite3*  database;


#pragma mark -
#pragma mark Check and Create Sqlite Table.
+ (void) CheckAndCreateDatabase {
    NSLog(@"\nCall of: CheckAndCreateDatabase");
    // Set database name.
    dataBaseName = @"Database.db";
    // Initialize database path.
    NSArray* paths         = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsDir = [paths objectAtIndex:0];
    dataBasePath           = [NSString stringWithFormat:@"%@/%@", documentsDir, dataBaseName];
    NSLog(@"Database Path is: %@", dataBasePath);
    NSLog(@"Database Name is: %@", dataBaseName);

    // 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.
    if( [fileManager fileExistsAtPath:dataBasePath] == NO ) {
        // Open database.
        if( sqlite3_open( [dataBasePath UTF8String], &database ) == SQLITE_OK ) {
            char* errorMsg;
            // Create Articles Table.
            const char* articlesTable = "CREATE TABLE [TableName] (textfieldm, text, textfieldn text)";
            if( sqlite3_exec(database, articlesTable, NULL, NULL, &errorMsg) != SQLITE_OK )
                NSLog( @"Fail to create [TableName] table. Error is: %@", errorMsg );


        } else NSLog(@"Fail to Create/Open database");
    }
    else {
        NSLog(@"Open database.");
        sqlite3_open( [dataBasePath UTF8String], &database );
    }
}

Вот как вы должны вставить

+ (void) insert {
    // Create Pre Sqlite query string.
    NSString* preSqliteQuery = @"INSERT INTO [TableName] (textfieldm, textfieldn VALUES ('%@', '%@')";

    // Create Sqlite query string.
    NSString* queryString = [NSString stringWithFormat:preSqliteQuery, Gunameq, Gpassq];
    // Execute query.
    sqlite3_exec(database, [queryString UTF8String], NULL, NULL, NULL);
}

Если я помогу, не забудьтеоценить меня !!!Удачи !!!

0 голосов
/ 19 апреля 2011
sqlite3_exec(database, [queryString UTF8String], NULL, NULL, NULL);
NSLog("Error is: %@");

Добавьте строку NSLog и просмотрите логи, после этого скажите, пожалуйста, какая ошибка возникает в вашем проекте. Может быть, таким образом я скажу тебе, что делать.

0 голосов
/ 18 апреля 2011

Вы можете попробовать таким образом

   NSString* str = [NSString stringwithformat:@"INSERT OR REPLACE INTO insert (textfieldm, textfieldn) VALUES ('%@', '%@')", Gunameq, Gpassq];
    if(sqlite3_exec(database, [str UTF8String], NULL, NULL, NULL) != SQLITE_DONE ) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"UIAlertView" message:@"Record added" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        [alert release];
        alert = nil;
}
else {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"UIAlertView" message:@"not Added" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        [alert release]; 
        alert = nil;
}

Я думаю, таким образом вы можете сделать это !!!Удачи !!!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...