【问题标题】:Values inserted in simulator but not showing in database table插入模拟器但未显示在数据库表中的值
【发布时间】:2011-08-07 18:37:37
【问题描述】:

我为插入记录的 SQLite 数据库创建了一个 insert 语句。我的代码工作正常——当我运行我的代码时,它会显示一条消息,指出添加了一条新记录。

当我打开 SQLite 浏览器查看记录是否已添加到数据库表时,记录没有出现。可能是什么问题呢?我的代码工作正常。它在模拟器中显示添加了联系人的消息,但在数据库中没有添加联系人。

这是我的代码:

#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];

}

【问题讨论】:

  • 放一些代码,这样任何人都可以尝试给你一些建议
  • 您是否已将数据库复制到您的文档目录中......并且您是否在插入后检查该副本中的数据?

标签: objective-c cocoa-touch ios sqlite


【解决方案1】:

你可以这样试试

   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;
}

我认为这样你就可以做到!!!祝你好运!!!

【讨论】:

  • 您所说的“我不必使用..”是什么意思?
  • 你为什么要使用这个功能?因为要在数据库中插入数据,您不需要使用该功能。 “sqlite3_prepare_v2_statement”用于创建编译语句以使用选择查询从数据库中获取数据..获取??
  • 还有“sqlite3_step”用于从编译语句中逐行获取数据,它不会执行你的查询..
  • 为什么要使用 sqlite3_prepare_v2_statement ???没有 sqlite3_prepare_v2_statement 也可以这样做!我觉得!!
  • link 在这里您可以阅读并找到您的问题的答案!!!
【解决方案2】:

.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);
}

如果我帮助你,别忘了给我打分!!!祝你好运!!!

【讨论】:

  • 你有没有安装sqlite管理器并用它检查你的数据库!!!如果您按照我在示例中给出的代码编写代码,它必须能够正常工作!!!
  • 你能不能把你想创建的文件发给我,以便我看到并纠正它!!!
【解决方案3】:
sqlite3_exec(database, [queryString UTF8String], NULL, NULL, NULL);
NSLog("Error is: %@");

添加 NSLog 行并查看之后的日志,请告诉我您的项目中发生了什么错误。也许这样我可以告诉你该怎么做。

【讨论】:

  • 我收到此错误:程序接收信号:“EXC_BAD_ACCESS”。杀死退出
  • 从这一行(sqlite3_exec(数据库,articlesTable,NULL,NULL,&errorMsg)!= SQLITE_OK)
  • 不要调用 [self chekAndCreateDatabase];从插入,因为每次按下按钮都会创建新表!!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-04
  • 2023-04-11
  • 2012-10-04
  • 2019-06-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多