我有两张桌子' table1'和' table_00'。我想将一些数据从table1移到table_00
我有这种方法来做到这一点:
- (void)moveData {
NSString *docsDir;
NSArray *dirPaths;
// 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:
@"MYDB_3.db"]];
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &myDatabase) == SQLITE_OK) {
NSString *insertSQL=@"INSERT INTO TABLE_00 SELECT * FROM TABLE_1 WHERE ID=00000" ;
const char *insert_stmt = [insertSQL UTF8String];
//i am using only one 'insertSQL', i put two 'insertSQL' strings here for reference
//mulitple statements
NSString *insertSQL=@"INSERT INTO TABLE_00 SELECT * FROM TABLE_1 WHERE UTILITYID='00000';"
"INSERT INTO TABLE_01 SELECT * FROM TABLE_1 WHERE UTILITYID='00001';"
"INSERT INTO TABLE_02 SELECT * FROM TABLE_1 WHERE UTILITYID='00002';"
"INSERT INTO TABLE_03 SELECT * FROM TABLE_1 WHERE UTILITYID='00003';";
//this multiple query statement is not working
sqlite3_prepare_v2(myDatabase, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE) {
NSLog(@"data moved");
} else {
NSLog(@"data not moved");
}
sqlite3_finalize(statement);
sqlite3_close(myDatabase);
}
在我调用此方法后,我可以使用单个查询来移动数据但是,我无法使用多个语句来移动数据。请您告诉我为什么会发生这种情况?
提前致谢。
答案 0 :(得分:1)
我认为你有一个额外的,应该是:
INSERT INTO TABLE_00 SELECT * FROM TABLE_1 WHERE ID= '00000'
更好的方法是使用占位符:
sqlite3_stmt *compiled = nil;
const char *sql = "INSERT INTO TABLE_00 SELECT * FROM TABLE_1 WHERE ID= ?";
sqlite3_prepare_v2(database, sql, -1, &compiled, NULL);
sqlite3_bind_text(compiled, 1, [yourId UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_step(compiled);
sqlite3_finalize(compiled);
答案 1 :(得分:0)
我使用for循环来执行多个语句。我就是这样做的
- (void)moveDatatoUtilityTables {
NSMutableArray *ID_Table=[[NSMutableArray alloc]init];
NSMutableArray *ID=[[NSMutableArray alloc]init];
[ID_Table addObject:@"TABLE_00"];
[ID_Table addObject:@"TABLE_01"];
[ID_Table addObject:@"TABLE_02"];
[ID addObject:@"00000"];
[ID addObject:@"00001"];
[ID addObject:@"00002"];
NSLog(@"database path is %@",databasePath);
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &myDatabase) == SQLITE_OK) {
for (int i=0; i<2; i++) {
NSString *insertSQL=[NSString stringWithFormat:@" INSERT INTO %@ SELECT * FROM TABLE_1 WHERE ID='%@'",[ID_Table objectAtIndex:i],[ID objectAtIndex:i]];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(myDatabase, insert_stmt,
-1, &statement, NULL);
// const char *sqlite3_column_name(sqlite3_stmt*, int N);
if (sqlite3_step(statement) == SQLITE_DONE) {
NSLog(@"data moved");
} else {
NSLog(@"data not moved");
}
sqlite3_finalize(statement);
}
sqlite3_close(myDatabase);
}
}