使用For循环插入或使用SQlite查询更新表时,它会正确地更新消息,并且在更新时也会出错。 '未知错误'错误消息也。插入正确完成但更新不起作用如果在SQLite管理器中运行更新查询它工作..谢谢提前
sqlite3 *database;
NSString * databaseName=[[NSString alloc]initWithString:DBName];
NSArray * documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString * databasePath = [[documentsDir stringByAppendingPathComponent:databaseName] retain];
NSString *lite;
BOOL check=[self isContainsID:filename];
if(check)
{
lite=[NSString stringWithFormat:@"INSERT INTO table_name(id,filename,date)VALUES('%@',%d,'%@')",id,filename,date];
}
else
{
lite=[NSString stringWithFormat:@"UPDATE table_name SET date='%@' where filename ='%@'",date,filename];
const char *sqlStatement = [lite UTF8String];
// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
// Setup the SQL Statement and compile it for faster access
sqlite3_stmt *compiledStatement=nil;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) != SQLITE_OK)
{
if(Debug)
{
DLog(@"not updated");
DLog(@"HMM, COULDNT RUN QUERY: %s\n", sqlite3_errmsg(database));
}
}
else
{
if (sqlite3_step(compiledStatement) == SQLITE_DONE)
{
DLog(@"updated successfully");
}
if(SQLITE_DONE != sqlite3_step(compiledStatement))
NSLog(@"Error while updating. '%s'", sqlite3_errmsg(database));
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
[databaseName release];
[databasePath release];
答案 0 :(得分:1)
此代码错误,导致调用sqlite3_step()
两次:
if (sqlite3_step(compiledStatement) == SQLITE_DONE)
{
DLog(@"updated successfully");
}
if(SQLITE_DONE != sqlite3_step(compiledStatement))
NSLog(@"Error while updating. '%s'", sqlite3_errmsg(database));
我确定你的意思是:
if (sqlite3_step(compiledStatement) == SQLITE_DONE)
{
DLog(@"updated successfully");
}
else
{
NSLog(@"Error while updating. '%s'", sqlite3_errmsg(database));
}
此外,您应该绑定语句变量,而不是将它们格式化为[NSString stringWithFormat:]
语句,因为它更安全并允许重复使用语句(这是准备的重点)它们)。