我已经成功地多次插入了大约 200 条记录,但我的问题是插入数据的顺序。记录插入到SD_0
, SD_1
, SD_10
, SD_100
, .. 等等。
我需要的订单是SD_0
, SD_1
, SD_2
, SD_3
,.... 等等。
这是我的查询:-
insert into Coffee (coffeeName,price) select ? as coffeeName ,? as price
UNION SELECT ? , ?
UNION SELECT ? , ?
UNION SELECT ? , ?
UNION SELECT ? , ?
UNION SELECT ? , ?
UNION SELECT ? , ?
UNION SELECT ? , ?
UNION SELECT ? , ?
UNION SELECT ? , ?
让我知道此查询是否需要任何更改。
我将此查询与 Objective-C 代码一起使用。
下面我添加代码:
-(void)addCoffee: (NSMutableDictionary *)dictParam {
NSString *strQuery = [NSString stringWithFormat:@"insert into Coffee (%@) select ? as %@",[[dictParam allKeys] componentsJoinedByString:@","],[[dictParam allKeys] objectAtIndex:0]];
//For second line of query SELECT 'data1' AS 'column1', 'data2' AS 'column2'
for (int i = 1; i<[dictParam count]; i++) {
strQuery = [strQuery stringByAppendingFormat:@" ,? as %@",[[dictParam allKeys] objectAtIndex:i]];
}
strQuery = [strQuery stringByAppendingFormat:@"\n"];
//For another union statements
for (int j = 1; j < [[dictParam valueForKey:[NSString stringWithFormat:@"%@",[[dictParam allKeys] objectAtIndex:0]]] count]; j++) {
strQuery = [strQuery stringByAppendingFormat:@"UNION SELECT ?"];
for (int i = 1; i<[dictParam count]; i++) {
strQuery = [strQuery stringByAppendingFormat:@" , ?"];
}
strQuery = [strQuery stringByAppendingFormat:@"\n"];
}
const char *sql = [strQuery UTF8String];
if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK)
NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));
int counter = 1;
for (int j = 0; j < [[dictParam valueForKey:[NSString stringWithFormat:@"%@",[[dictParam allKeys] objectAtIndex:0]]] count]; j++) {
for (int i = 0; i<[dictParam count]; i++) {
sqlite3_bind_text(addStmt, counter, [[NSString stringWithFormat:@"%@",[[dictParam valueForKey:[NSString stringWithFormat:@"%@",[[dictParam allKeys] objectAtIndex:i]]] objectAtIndex:j]] UTF8String], -1, SQLITE_TRANSIENT);
counter++;
}
}
if(SQLITE_DONE != sqlite3_step(addStmt))
NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
else
coffeeID = sqlite3_last_insert_rowid(database);
//Reset the add statement.
sqlite3_reset(addStmt);
}