无法在sqlite3数据库中插入联系人

时间:2014-11-10 07:15:01

标签: ios objective-c sqlite

-(IBAction)saveData:(UIButton *)sender { 
    sqlite3_stmt *statement; 
const char *dbpath = [databasePath UTF8String]; 

if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK) 
{ 

    NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO CONTACTS (name , password , email) VALUES (\"%@\", \"%@\", \"%@\")",
                          self.theName.text ,self.thePass.text,self. Email.text]; 

    const char *insert_stmt = [insertSQL UTF8String]; 

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

    if (sqlite3_step(statement) == SQLITE_DONE) 
    { 
        self.theStatus.text = @"Contact added"; 
        self.theName.text = @""; 
        self.Email.text = @""; 
        self.thePass.text = @""; 
    }
    else { 
        self.theStatus.text = @"Failed to add contact"; 
    } 
    sqlite3_finalize(statement); 
    sqlite3_close(contactDB); 
}} 

我正在使用此代码将我的数据插入sqlite数据库。但它始终显示相同的答案“未能添加联系人”。

1 个答案:

答案 0 :(得分:0)

使用此选项可获取所需的所有错误消息

-(IBAction)saveData:(UIButton *)sender { 
sqlite3_stmt *statement; 
const char *dbpath = [databasePath UTF8String]; 

if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK) 
{
    NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO CONTACTS (name , password , email) VALUES (\"%@\", \"%@\", \"%@\")",
                          self.theName.text ,self.thePass.text,self. Email.text]; 

    const char *insert_stmt = [insertSQL UTF8String]; 

    if (sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL) == SQLITE_OK)
    {
        if (sqlite3_step(statement) == SQLITE_DONE) 
        { 
            self.theStatus.text = @"Contact added"; 
            self.theName.text = @""; 
            self.Email.text = @""; 
            self.thePass.text = @""; 
        }
        else { 
            NSLog(@"sqlite3_step failed: %s", sqlite3_errmsg(contactDB));
            self.theStatus.text = @"Failed to add contact"; 
        }

        sqlite3_finalize(statement);
    }
    else
    {
        NSLog(@"sqlite3_prepare_v2 failed: %s", sqlite3_errmsg(contactDB));
    }

    sqlite3_close(contactDB); 
}
else
{
    NSLog(@"sqlite3_open failed: %s", sqlite3_errmsg(contactDB));
}
}

这可能没有错误,因为我无法测试它的编译,但是这可以让你知道如何得到错误。