【发布时间】:2014-10-25 15:00:40
【问题描述】:
伙计们,我的 sn-p 有问题。我还必须说我是新手。我正在尝试将数据插入到 sqlite。但我一直失败,因为 sqlite_step == sqlite_done 一直返回 false 。我在这里做错什么了吗。我以前做过类似的事情,而且效果很好。以下是代码
sqlite3_stmt *statement;
const char *dbpath = [_databasePath UTF8String];
if(sqlite3_open(dbpath, &_db) == SQLITE_OK){
NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO userInfo (name, email, username, password) VALUES (\"%@\",\"%@\",\"%@\",\"%@\")", self.txtName.text, self.txtEmail.text, self.txtUsername.text, self.txtPassword.text];
if([self validateRegistration])
{
const char *insert_statement = [insertSQL UTF8String];
sqlite3_prepare_v2(_db, insert_statement, -1, &statement, NULL);
if(sqlite3_step(statement) == SQLITE_DONE){
[self showUIAlertWithMessage:@"User added to the database" andTitle:@"Message"];
self.txtName.text = @"";
self.txtEmail.text = @"";
self.txtUsername.text = @"";
self.txtPassword.text = @"";
self.txtConfirmPassword.text = @"";
}else{
[self showUIAlertWithMessage:@"Failed to add the user" andTitle:@"Error"];
}
sqlite3_finalize(statement);
sqlite3_close(_db);
}
}
【问题讨论】:
-
捕获返回码并记录“坏”的值,不要简单地测试它们。并捕获其中的所有。然后在收到错误的返回码时记录来自 sqlite3_errmsg 的值。
-
使用 +[NSString stringWithFormat:] 构造 SQLite 语句是个坏主意。最好的情况是,当用户输入双引号字符或类似字符时,您会遇到莫名其妙的错误。在最坏的情况下,它可能会让您对来自恶意用户的 SQL 注入持开放态度。您应该改用占位符和
sqlite3_bind_*API 来安全地执行此操作。
标签: ios objective-c iphone sqlite ios8.1