【发布时间】:2014-04-14 18:18:51
【问题描述】:
我一直在使用以下代码更新我的 sqlite 表中的数据,但一直认为这不是最佳方式。基本上,因为我不知道我的二维 NSMutableArray 中的数据是什么以及在哪里被用户更新了,所以我正在做的是删除表,用所有列再次创建它,然后在其中插入数据。
通过表和我的数组之间的某种数据比较,有没有更好的方法来做到这一点。请指出您在以下方面看到的任何其他不当行为:
-(void)updateCurrentItemsData:(NSArray *) dataArray
{
NSArray *paths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory=[paths objectAtIndex:0];
gameDBPath=[documentsDirectory stringByAppendingPathComponent:@"gameData.sqlite"];
const char *dbpath = [gameDBPath UTF8String];
int test;
char *errMsg;
if (sqlite3_open(dbpath, &gamedatabase)==SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:@"DELETE FROM currentitems"];
const char *query_stmt = [querySQL UTF8String];
test=sqlite3_exec(gamedatabase, query_stmt, NULL, NULL, &errMsg);
if (test!=0) NSLog(@"exec is 5 1 %i",test);
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS currentitems(itemid, name, quantity, damaged, price)";
test=sqlite3_exec(gamedatabase, sql_stmt, NULL, NULL, &errMsg);
if (test!=0) NSLog(@"exec is 5 2 %i",test);
for (int i=0; i<dataArray.count; i++)
{
NSString *querySQL= [NSString stringWithFormat:@"INSERT INTO currentitems(itemid, name, quantity, damaged, price) VALUES('%i','%@','%i','%i','%i')",[[[dataArray objectAtIndex:i] objectAtIndex:0] intValue],[[dataArray objectAtIndex:i] objectAtIndex:1],[[[dataArray objectAtIndex:i] objectAtIndex:2] intValue],[[[dataArray objectAtIndex:i] objectAtIndex:3] intValue],[[[dataArray objectAtIndex:i] objectAtIndex:4] intValue]];
//NSLog(@"querySQL is %@",querySQL);
const char *insert_stmt= [querySQL UTF8String];
test=sqlite3_exec(gamedatabase, insert_stmt, NULL, NULL, &errMsg);
if (test!=0) NSLog(@"exec is 5 3 %i",test);
}
sqlite3_finalize(statementgame);
sqlite3_close(gamedatabase);
}
}
感谢收看 :)
【问题讨论】:
标签: ios sql objective-c sqlite