SQLite在Android系统中的使用方法(3)

发表于:2013-01-04来源:ImportNew作者:赵荣点击数: 标签:Android
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 @Override public void onCreate(SQLiteDatabase database) { executeSQLScript(database, create.sql ); } private v

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@Override
public void onCreate(SQLiteDatabase database) {
    executeSQLScript(database, "create.sql");
}
 
private void executeSQLScript(SQLiteDatabase database, string dbname){
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte buf[] = new byte[1024];
        int len;
        AssetManager assetManager = context.getAssets();
        InputStream inputStream = null;
 
        try{
            inputStream = assetManager.open(dbname);
            while ((len = inputStream.read(buf)) != -1) {
                   outputStream.write(buf, 0, len);
                }
            outputStream.close();
            inputStream.close();
                String[] createScript = outputStream.toString().split(";");
                for (int i = 0; i < createScript.length; i++) {
                    String sqlStatement = createScript[i].trim();
                    // TODO You may want to parse out comments here
                    if (sqlStatement.length() > 0) {
                        database.execSQL(sqlStatement + ";");
                    }
            }
       } catch (IOException e){
            // TODO Handle Script Failed to Load
        } catch (SQLException e) {
            // TODO Handle Script Failed to Execute
       }
}

原文转自:http://www.ltesting.net