android, how to exec a sql file in sqlitedatabase

前端 未结 4 974
孤街浪徒
孤街浪徒 2020-12-01 02:18

i have \"food_db.sql\" file stored in /res/raw folder, it has tons of \'insert\' in it.

my question is how to i exec the file and get the data into sqlite databse in

4条回答
  •  北海茫月
    2020-12-01 02:44

    Insert all line in one string:

    public int insertFromFile(Context context, int resourceId) throws IOException {
        // Reseting Counter
        int result = 0;
    
    // Open the resource
    InputStream insertsStream = context.getResources().openRawResource(resourceId);
    BufferedReader insertReader = new BufferedReader(new InputStreamReader(insertsStream));
    
    // Iterate through lines (assuming each insert has its own line and theres no other stuff)
    String insertStmt = "";
    while (insertReader.ready()) {
        insertStmt += insertReader.readLine();
        result++;
    }
    insertReader.close();
    
    db.execSQL(insertStmt);
    
    // returning number of inserted rows
    return result;
    }
    

提交回复
热议问题