内容来源于 Stack Overflow,遵循 CC BY-SA 4.0 许可协议进行翻译与使用。IT领域专用引擎提供翻译支持
腾讯云小微IT领域专用引擎提供翻译支持
我有两个SQLite数据库,有相同的数据,但用途不同,我想避免重新插入数据,所以我想知道是否可以将整个表从一个数据库复制到另一个数据库?
您必须使用 ATTACH 命令将数据库X与数据库Y连接起来,然后为要传输的表运行适当的Insert Into命令。
INSERT INTO X.TABLE SELECT * FROM Y.TABLE;
或者,如果列没有按顺序匹配:
INSERT INTO X.TABLE(fieldname1, fieldname2) SELECT fieldname1, fieldname2 FROM Y.TABLE;
将表从一个数据库复制到另一个数据库的Objective-C代码
-(void) createCopyDatabase{ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES); NSString *documentsDir = [paths objectAtIndex:0]; NSString *maindbPath = [documentsDir stringByAppendingPathComponent:@"User.sqlite"];; NSString *newdbPath = [documentsDir stringByAppendingPathComponent:@"User_copy.sqlite"]; NSFileManager *fileManager = [NSFileManager defaultManager]; char *error; if ([fileManager fileExistsAtPath:newdbPath]) { [fileManager removeItemAtPath:newdbPath error:nil]; sqlite3 *database; //open database if (sqlite3_open([newdbPath UTF8String], &database)!=SQLITE_OK) { NSLog(@"Error to open database"); NSString *attachQuery = [NSString stringWithFormat:@"ATTACH DATABASE \"%@\" AS aDB",maindbPath]; sqlite3_exec(database, [attachQuery UTF8String], NULL, NULL, &error); if (error) { NSLog(@"Error to Attach = %s",error); //Query for copy Table NSString *sqlString = @"CREATE TABLE Info AS SELECT * FROM aDB.Info"; sqlite3_exec(database, [sqlString UTF8String], NULL, NULL, &error); if (error) { NSLog(@"Error to copy database = %s",error); //Query for copy Table with Where Clause sqlString = @"CREATE TABLE comments AS SELECT * FROM aDB.comments Where user_name = 'XYZ'"; sqlite3_exec(database, [sqlString UTF8String], NULL, NULL, &error); if (error) { NSLog(@"Error to copy database = %s",error);