android, how to exec a sql file in sqlitedatabase

前端 未结 4 982
孤街浪徒
孤街浪徒 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:42

    The best way is parsing sql file, split file into statement list.

    It not hard cause we only need to take care of commit, string and escape, but it not easy too write one in short time.

    I found an easy way to archive this by replacing comment string by using regex, from SugarORM source code(https://github.com/chennaione/sugar/blob/master/library/src/main/java/com/orm/util/MigrationFileParser.java)

    public MigrationFileParser(String content){
        this.content = content.replaceAll("(\\/\\*([\\s\\S]*?)\\*\\/)|(--(.)*)|(\n)","");
    }
    
    public String[] getStatements(){
        return this.content.split(";");
    }
    

    This way has limitation(we can't use "/*", "--" in sql string), but will be ok in most case.

    hope this help

提交回复
热议问题