如何以编程方式在android上执行* .sql脚本?

时间:2012-11-24 05:16:08

标签: android sqlite

如何以编程方式在android上执行* .sql脚本? 该脚本位于/ assert文件夹中。我的手机没有扎根。

1 个答案:

答案 0 :(得分:6)

InputStream is = getResources().getAssets().open("SQLScript.sql");
String sql= convertStreamToString(is);

public static String convertStreamToString(InputStream is)
            throws IOException {
            Writer writer = new StringWriter();
        char[] buffer = new char[2048];
        try {
            Reader reader = new BufferedReader(new InputStreamReader(is,
                    "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        String text = writer.toString();
        return text;
}


SQLiteDatabase db;
db = openOrCreateDatabase("MyDatabase.db", SQLiteDatabase.CREATE_IF_NECESSARY, null );
db.execSQL(sql);