2015-07-19 169 views
0

我寫了下面的代碼,從另一個數據庫的表中插入一些記錄到表中。
但我無法執行sql語句後,它表明表中沒有記錄。Sqllite插入查詢多個數據庫

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 

因此,沒有記錄已被插入。

回答

2

您正在使用rawQuery()執行INSERT 命令。其中將永遠不會工作
使用execSQL(),而不是

而且,最後的評論是一種誤導,因爲它說,你想從NEW表計數,但你從OLD一個計數。

而且,請擺脫字符串分隔符')。
即:

String new_query =" SELECT * FROM 'NEW'.'"+ TABLE_CONTACTS +"'"; 

應該

String new_query = "SELECT * FROM NEW." + TABLE_CONTACTS; 
+1

感謝ü它的工作原理 –