需要帮助在iOS中插入查询

时间:2016-03-30 07:43:02

标签: ios iphone database xcode sqlite

我在这里尝试学习sqlite数据库。

我正在使用firefox的Sqlite Manager来创建数据库表。

我想将数据插入到表中,但是当我在textfield中插入一些数据然后按下插入按钮时,我的数据表仍然是空的。我无法在表格中插入数据

这里我包含了我的代码

在DBManager.h文件中

@interface DBManager : NSObject
{
    NSString *databasePath;
}

+(DBManager *) getSharedInstance;

-(void)CreateDB;

-(BOOL)InsertData:(NSString*)Name Email:(NSString*)Email City:(NSString*)City State:(NSString*)State;;

在DBManager.m文件中

@implementation DBManager

+(DBManager*) getSharedInstance
{
    if (!SharedInstance) {
        SharedInstance = [[super allocWithZone:NULL]init];
        [SharedInstance CreateDB];
    }
    return SharedInstance;


}


-(void)CreateDB
{
    NSString *documentDirectory;
    NSArray *directoryPath;

    //=== GET THE DOCUMENT DIRECTORY=====//

    directoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    documentDirectory =directoryPath[0];

    databasePath = [[NSString alloc] initWithString:
                    [documentDirectory stringByAppendingPathComponent: @"StudentInformation.sqlite"]];

    NSFileManager *fileManager=[NSFileManager defaultManager];

    if (![fileManager fileExistsAtPath:databasePath])
    {
        NSString *fromPath = [[NSBundle mainBundle]pathForResource:@"StudentInformation" ofType:@"sqlite"];
        [fileManager copyItemAtPath:fromPath toPath:documentDirectory error:nil];
    }

}

-(BOOL)InsertData:(NSString*)Name Email:(NSString*)Email City:(NSString*)City State:(NSString*)State
{
    const char *DBPath = [databasePath UTF8String];

    if (sqlite3_open(DBPath, &database)==SQLITE_OK)
    {
        NSString *inserSQLQuery = [NSString stringWithFormat:@"insert into StudentInfo (Name, Email, City, State)values(\"%@\",\"%@\",\"%@\",\"%@\")", Name, Email, City, State];

        const char *insert_stmt = [inserSQLQuery UTF8String];

        sqlite3_prepare_v2(database, insert_stmt, -1, &statement, NULL);

        if (sqlite3_step(statement)==SQLITE_DONE)
        {
            return YES;
        }
        else
        {
            return NO;
        }
//        sqlite3_finalize(statement);
    }
//    sqlite3_close(database);
    sqlite3_close(statement);
    return YES;
}
@end
viewcontroller.m文件中的

//insert btn clicked
- (IBAction)btnSaveClicked:(id)sender
{
    NSString *strName = txtName.text;
    NSString *strEmail = txtEamil.text;
    NSString *strCity = txtCity.text;
    NSString *strState = txtState.text;

    [[DBManager getSharedInstance]InsertData:strName Email:strEmail City:strCity State:strState];

    NSLog(@"Done");
}

我可能错误地插入查询,所以请向我提供此问题的指导。

谢谢

0 个答案:

没有答案