복붙노트

[SQL] 안드로이드, 방법의 SQLiteDatabase에서 SQL 파일을 간부 인하는

SQL

안드로이드, 방법의 SQLiteDatabase에서 SQL 파일을 간부 인하는

나는 "food_db.sql"파일 / 입술 / 원시 폴더에 저장 한 그것의 '삽입'의 톤이있다.

내 질문에 내가 어떻게에 파일을 간부 인 내 안드로이드 응용 프로그램에서 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);
    }

}

해결법

  1. ==============================

    1.내가 당신을 위해, 특히이 하나를 쓴 <3

    내가 당신을 위해, 특히이 하나를 쓴 <3

    난 당신이 "/raw/food_db.sql"와 같은 파일 이름을 사용하지만 오류에 그 리드 대신 나는 "/ 생 /의 food_db"를 호출했다. 난 당신의 코드는 사용하지 않기 때문에 파일 이름을 추측하지만, ResourceIds한다 "는 R.raw.food_db"와 같은 기록 된 도트 시스템을 혼동한다.

    당신의 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;
    }
    

    (그래서 토스트 출력 할 수 메시지, 내가 활동에서 시도)과 같이 호출. 봐 밀접하게 오류가 아니라 "토스트"입니다.

    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 :이 코드는 각 삽입 문은 자신의 라인을 가지고있는 파일을 의미한다.

  2. ==============================

    2.

    @Override
    public void onCreate(SQLiteDatabase db) {
        InputStream is = null;
        try {
            is = context.getResources().openRawResource(R.raw.database_init);
            String initSql = IOUtils.toString(is);
            db.execSQL(initSql);
        } catch (IOException e) {
            Log.e(TAG, "Error loading init SQL from raw", e);
        } catch (SQLException e) {
            Log.e(TAG, "Error executing init SQL", e);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
    

    중요한 선은 SQLiteDatabase.execSQL (문자열 SQL)이 단 하나의 SQL 문을 실행하고, 세미콜론으로 구분 된 여러 문은 지원되지 않습니다.

    나는 예상대로 내 database_init.sql 작업하지 않는 이유를 찾기 위해 힘든 시간을 시도했습니다.

  3. ==============================

    3.하나 개의 문자열에있는 모든 행을 삽입합니다

    하나 개의 문자열에있는 모든 행을 삽입합니다

    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;
    }
    
  4. ==============================

    4.가장 좋은 방법은 문 목록에 SQL 파일, 분할 파일을 구문 분석됩니다.

    가장 좋은 방법은 문 목록에 SQL 파일, 분할 파일을 구문 분석됩니다.

    우리는 단지 문자열과 탈출을 커밋 알아서해야하지만 쉽게 너무 짧은 시간에 일을 쓸 그것은 어려운 일이 아니다 원인.

    나는 SugarORM 소스 코드에서, 정규식을 사용하여 설명 문자열을 대체하여이를 보관하는 쉬운 방법 (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(";");
    }
    

    (- SQL 문자열에 ""우리가 사용할 수 없습니다 "/ *")하지만, 대부분의 경우에 확인 될 것입니다이 방법은 한계가있다.

    이 도움말을 희망

  5. from https://stackoverflow.com/questions/8199138/android-how-to-exec-a-sql-file-in-sqlitedatabase by cc-by-sa and MIT license