我在/ res / raw文件夹中存储了“food_db.sql”文件,
它里面有大量的“插入”。

我的问题是如何执行该文件并将数据放入我的android应用程序中的sqlite数据库?

这是我的数据库代码。有什么建议吗?

private static class DbHelper extends SQLiteOpenHelper{

    public DbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        // TODO Auto-generated constructor stub
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
                KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                KEY_NAME + " TEXT NOT NULL, " +
                KEY_HOTNESS + " TEXT NOT NULL);");
                    // how do i exec the sql file and get the data into this DB table?
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS" + DATABASE_TABLE);
        db.execSQL("DROP TABLE IF EXISTS" + RECORD_TABLE);
        onCreate(db);
    }

}

最佳答案

我特别为你写了这本
我使用了与您相同的文件名“/raw/food_db.sql” ,但该导致错误,我不得不将其命名为“/ raw / food_db” 。我猜是因为您没有在代码中使用文件名,而是像“R.raw.food_db”这样写的ResourceId和点使系统感到困惑。

在您的DbSource中有一个方法...假设某处有这样的代码:

private SQLiteDatabase db;
...
DbHelper dbHelper = new DbHelper(context);
this.db = dbHelper.getWritableDatabase();

您将此方法放在其中:
/**
 * This reads a file from the given Resource-Id and calls every line of it as a SQL-Statement
 *
 * @param context
 *
 * @param resourceId
 *  e.g. R.raw.food_db
 *
 * @return Number of SQL-Statements run
 * @throws IOException
 */
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)
    while (insertReader.ready()) {
        String insertStmt = insertReader.readLine();
        db.execSQL(insertStmt);
        result++;
    }
    insertReader.close();

    // returning number of inserted rows
    return result;
}

这样称呼它(我在一个Activity中尝试过,以便Toasts可以输出消息)。仔细观察,错误也是“敬酒的”。
try {
        int insertCount = database.insertFromFile(this, R.raw.food_db);
        Toast.makeText(this, "Rows loaded from file= " + insertCount, Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }

请享用!

哦.. btw:此代码适用于每个insert-Statement都有其自己行的文件。

07-28 01:49
查看更多