我编写了以下代码,将一些记录从另一个数据库的表中插入到表中 但我无法做到,即使在执行sql语句后,它也显示表中没有记录。
public int copy_to_all_source_table(String dbpath,String backpath)
{
SQLiteDatabase db1 = this.getWritableDatabase();
//Opening App database(i.e. dbpath) and attaching it as "OLD"
db1.openDatabase(dbpath, null, SQLiteDatabase.OPEN_READWRITE);
String attach_old="ATTACH '"+ dbpath +"' AS OLD";
db1.execSQL(attach_old);
//Opening New File which is Student.db(i.e. dbpath) and attaching it as "NEW"
db1.openDatabase(backpath, null, SQLiteDatabase.OPEN_READWRITE);
String attach_new="ATTACH '"+ backpath +"' AS NEW";
db1.execSQL(attach_new);
// Getting count of records in table of "NEW"
String new_query =" SELECT * FROM 'NEW'.'"+ TABLE_CONTACTS +"'";
Cursor new_data = db1.rawQuery(new_query, null);
Integer new_count= new_data.getCount();
//INSERTING ALL RECORDS FROM TABLE OF NEW TO TABLE OF OLD
String insert_query ="INSERT INTO 'OLD'.'"+ TABLE_CONTACTS +"' SELECT * FROM 'NEW'.'"+ TABLE_CONTACTS +"'";
Cursor success_insert = db1.rawQuery(insert_query, null);
// Getting count of records in table of "NEW"
String after_insert_old_query =" SELECT * FROM 'OLD'.'"+ TABLE_CONTACTS +"'";
Cursor old_data = db1.rawQuery(after_insert_old_query, null);
Integer old_count= old_data.getCount();
}
结果:
new_count = 11
old_count = 0
所以,没有插入任何记录。
答案 0 :(得分:2)
您正在使用rawQuery()
执行INSERT 命令。哪个永远不会工作
请使用execSQL()
,而不是
此外,最后一条评论具有误导性,因为它表示您希望从新表中计算,但您从 OLD 表中计算。
并且,请摆脱字符串分隔符(')。
即:
此
String new_query =" SELECT * FROM 'NEW'.'"+ TABLE_CONTACTS +"'";
应该是
String new_query = "SELECT * FROM NEW." + TABLE_CONTACTS;