插入命令失败,返回码为SQLITE_ERROR

时间:2017-01-17 08:23:51

标签: ios objective-c macos sqlite

我有一个sqlite3数据库,当将数据插入db时,它总是失败并返回代码SQLITE_ERROR

例如,sqlite3_prepare_v2总是失败。

NSString *sql = [NSString stringWithFormat:@"insert into t_elementnode(opname,op,param) values('%@',%ld,'%@')",elementNode.name,elementNode.operation,elementNode.paramString];
sqlite3_stmt *stmt;
int result = sqlite3_prepare_v2(db, [sql UTF8String], -1, &stmt, NULL);
if (result != SQLITE_OK) {
NSLog(@"====exit:%@,result:%d,op:%ld,param:%@",elementNode.name,result,elementNode.operation,elementNode.paramString);
return;
}

sqlite3_bind_text(stmt, 1, elementNode.name.UTF8String, -1, NULL);
sqlite3_bind_int64(stmt, 2, elementNode.operation);
sqlite3_bind_text(stmt, 3, elementNode.paramString.UTF8String, -1, NULL);

result = sqlite3_step(stmt);
if (result != SQLITE_DONE) {
    sqlite3_finalize(stmt);
    NSLog(@"===insert error:%d",result);
    return;
}

sqlite3_finalize(stmt);

NSLog输出是:

====退出:标题,结果是:1时,运算:11,PARAM:{   " locatorType" :6,   " locatorValue" :" // XCUIElementTypeLink [@name =' title']" }

1 个答案:

答案 0 :(得分:0)

通过更改命令解决问题,不要使用字符串连接,格式,%等将参数传递给查询;

char * sql2 = "insert into t_elementnode(opname,op,param) values(?,?,?)";
if(elementNode.opname) sqlite3_bind_text(stmt, 1, elementNode.opname.UTF8String, -1, NULL);
if(elementNode.op) sqlite3_bind_text(stmt, 2, elementNode.op.UTF8String, -1, NULL);
if(elementNode.param) sqlite3_bind_text(stmt, 3, elementNode.param.UTF8String, -1, NULL);