[英]How do I insert string to sqlite in Objective-C?
我無法將NSMutableString
插入sqlite。 我從Web服務器成功獲取了信息,並成功創建了sqlite文件,但是無法將Web中的數據插入sqlite。
我認為問題就在這里。
NSString *insertSQL = @"INSERT INTO Questions VALUES (result)";
但我不確定,無法解決此問題。 有人可以幫我嗎?
- (void)getInforamtionFromWeb {
NSURL *url = [NSURL URLWithString:kGetUrl];
data = [NSData dataWithContentsOfURL:url];
NSError *error;
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
result = [[NSMutableString alloc] init];
for (NSObject * obj in json)
{
[result appendString:[obj description]];
}
}
-(void)initiatSqlite{
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
// Build the path to the database file
_databasePath = [[NSString alloc]
initWithString: [docsDir stringByAppendingPathComponent:
@"Questions.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: _databasePath ] == NO)
{
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt =
"CREATE TABLE IF NOT EXISTS Questions (ID INTEGER PRIMARY KEY AUTOINCREMENT, Question Text, AnswerA Text, AnswerB Text, AnswerC Text, AnswerD Text, CorrectAnswer Text, Explanation Text)";
if (sqlite3_exec(_contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
[self Worningtitle:@"Error" Message:@"Failed to create table"];
}
sqlite3_close(_contactDB);
} else {
[self Worningtitle:@"Error" Message:@"Failed to open/create database"];
}
}
}
- (void) insertData
{
sqlite3_stmt *statement;
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
NSString *insertSQL = @"INSERT INTO Questions VALUES (result)";
const char *insert_stmt = [insertSQL UTF8String];
NSLog(@"%s",insert_stmt);
sqlite3_prepare_v2(_contactDB, insert_stmt, -1, &statement, NULL);
sqlite3_bind_text(statement, 1, [result UTF8String], -1, SQLITE_TRANSIENT);
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(@"Product added");
} else {
NSLog(@"Failed to add Product");
}
sqlite3_finalize(statement);
sqlite3_close(_contactDB);
}
}
你是對的。 您的INSERT
語句不正確。 它必須是:
NSString *insertSQL = @"INSERT INTO Questions VALUES (?)";
?
是將應用sqlite3_bind_xxx
。
請記住,您的Questions
表有很多列,但是您只插入一個值。 您應指定該值應插入到哪一列。 例:
NSString *insertSQL = @"INSERT INTO Questions (Question) VALUES (?)";
用要輸入result
值的正確列名替換“ Question
。
順便說一句-您的代碼需要做很多工作才能使其變得更好。 您需要添加更多錯誤檢查,尤其是使用sqlite3_prepare_v2
。
基於要插入更多數據,您可以執行以下操作:
- (BOOL)insertData {
BOOL result = NO; // failed
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK) {
const char *insert_stmt = "INSERT INTO Questions(AnswerA,AnswerB,AnswerC,AnswerD,CorrectAnswer,Question) VALUES (?,?,?,?,?,?)";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(_contactDB, insert_stmt, -1, &statement, NULL) == SQLITE_OK) {
sqlite3_bind_text(statement, 1, [answerA UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 2, [answerB UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 3, [answerC UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 4, [answerD UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 5, [correctAnswer UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 6, [question UTF8String], -1, SQLITE_TRANSIENT);
if (sqlite3_step(statement) == SQLITE_DONE) {
NSLog(@"Product added");
result = YES;
} else {
NSLog(@"Failed to add Product: %s", sqlite3_errmsg(_contactDB));
}
sqlite3_finalize(statement);
} else {
NSLog(@"Unable to prepare statement: %s", sqlite3_errmsg(_contactDB);
}
sqlite3_close(_contactDB);
} else {
NSLog(@"Unable to open database: %@", sqlite3_errmsg(_contactDB));
}
return result;
}
請注意,您需要使用對包含每個列數據的實際變量/值的引用來更新每個sqlite3_bind_text
調用。
您也不需要綁定ID
值,因為它已設置為自動填充。
注意所有正確的錯誤檢查。 我也這樣做了,所以insertData
返回一個BOOL
指示是否成功添加了數據。
試聽所有表的通用方法:
+(BOOL)insertWithReturnConfirmInTable:(NSString *)tableName Param:(NSDictionary *)params
{
NSArray *keys = [[NSArray alloc] initWithArray:[self GetColumnsForTable:tableName]];
//insert statement
NSString *query = [NSString stringWithFormat:@"INSERT INTO %@(",tableName];
//set keys
for (int i=0; i<[keys count]; i++) {
if([keys objectAtIndex:i] == [keys lastObject])
{
query = [query stringByAppendingString:[NSString stringWithFormat:@"%@) VALUES (",[keys objectAtIndex:i]]];
for (int m=0; m<[keys count]; m++) {
if([keys objectAtIndex:m] == [keys lastObject])
query = [query stringByAppendingString:@"?)"];
else
query = [query stringByAppendingString:@"?,"];
}
}
else
{
query = [query stringByAppendingString:[NSString stringWithFormat:@"%@,",[keys objectAtIndex:i]]];
}
}
NSLog(@"Query : %@",query);
if (sqlite3_open([[self getDBPath] UTF8String], &dbObj) == SQLITE_OK) {
sqlite3_stmt *addStmt = nil;
if (sqlite3_prepare_v2(dbObj, [query UTF8String], -1, &addStmt, NULL) != SQLITE_OK)
NSAssert1(0, @"Error while creating insert statement. '%s'",sqlite3_errmsg(dbObj));
//for Values
for (int i=0; i<[keys count]; i++) {
sqlite3_bind_text(addStmt, i+1, [[NSString stringWithFormat:@"%@",[params objectForKey:[keys objectAtIndex:i]]] UTF8String], -1, SQLITE_TRANSIENT);
}
if (SQLITE_DONE != sqlite3_step(addStmt)) {
NSLog(@"Error while inserting data. '%s'", sqlite3_errmsg(dbObj));
sqlite3_close(dbObj);
return NO;
}
else {
sqlite3_finalize(addStmt);
NSLog(@"data inserted in table : %@",tableName);
sqlite3_close(dbObj);
return YES;
}
} else {
NSLog(@"Error in opening database.");
sqlite3_close(dbObj);
return NO;
}
}
}
調用方法:將所有字段名稱作為鍵,將所有值作為字典中的值。 並傳遞表名。
NSDictionary *param = [[NSDictionary alloc]initWithObjectsAndKeys:@"1",@"S_Id",@"abc",@"Name", nil];
[database insertInTable:@"Child" Param:param];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.