2015-04-27 3 views
0

Я пытаюсь преобразовать свою базу данных в файл csv, но у меня сумасшедшая проблема. Я около года в кодировании, поэтому мне было очень тяжело.Преобразование базы данных в CSV-файл

вот мой код, чтобы сделать файл csv. Он создает файл, но по какой-то причине он создает пустой файл вместо файла csv со всеми данными из базы данных.

public class ExportDatabaseToCSV{ 

static Context context; 
public ExportDatabaseToCSV(Context context) { 
    this.context=context; 
} 

public static void exportDataBaseIntoCSV(){ 


    Database db = new Database(context);//here CredentialDb is my database. you can create your db object. 
    File exportDir = new File(Environment.getExternalStorageDirectory(), ""); 

    if (!exportDir.exists()) 
    { 
     exportDir.mkdirs(); 
    } 

    File file = new File(exportDir, "csvfilename.csv"); 

    try 
    { 
     file.createNewFile(); 
     CSVWriter csvWrite = new CSVWriter(new FileWriter(file)); 
     SQLiteDatabase sql_db = db.getReadableDatabase();//here create a method ,and return SQLiteDatabaseObject.getReadableDatabase(); 
     Cursor curCSV = sql_db.rawQuery("SELECT * FROM "+Database.DATABASE_TABLE,null); 
     csvWrite.writeNext(curCSV.getColumnNames()); 

     while(curCSV.moveToNext()) 
     { 
      //Which column you want to exprort you can add over here... 
      String arrStr[] ={curCSV.getString(0),curCSV.getString(1), curCSV.getString(2)}; 
      csvWrite.writeNext(arrStr); 
     } 

     csvWrite.close(); 
     curCSV.close(); 
    } 
    catch(Exception sqlEx) 
    { 
     Log.e("Error:", sqlEx.getMessage(), sqlEx); 
    } 
} 

}

try 
    { 

     File file = new File(exportDir, "csvfilename.csv"); 
     file .setReadable(true, false); 
     file .setWritable(true,false); 

     CSVWriter csvWrite = new CSVWriter(new FileWriter(file)); 
     SQLiteDatabase sql_db = db.openOrCreateDatabase("community_service_Database", Context.MODE_PRIVATE, null); 
     Cursor curCSV = sql_db.rawQuery("SELECT * FROM "+Database.DATABASE_TABLE,null); 
     csvWrite.writeNext(curCSV.getColumnNames()); 

     while(curCSV.moveToNext()) 
     { 
      //Which column you want to export you can add over here... 
      String arrStr[] ={curCSV.getString(0),curCSV.getString(1), curCSV.getString(2)}; 
      csvWrite.writeNext(arrStr); 

      csvWrite.close(); 
      curCSV.close(); 
     } 
    } 
    catch(Exception sqlEx) 
    { 
     Log.e("Error:", sqlEx.getMessage(), sqlEx); 
    } 
} 

}

ответ

0

Конструктор Файл будет уже создан файл для вас. Возможно, вам потребуется настроить его на чтение и запись.

File file = new File(exportDir, "csvfilename.csv"); 
file .setReadable(true, false); 
file .setWritable(true,false); 

Я предлагаю вам просто расширить класс SQLiteOpenHelper:

public static class DBHelper extends SQLiteOpenHelper 
    { 
    public DBHelper(Context context) 
    { 
     super(context, "community_service_Database", null, 1); 
    } 

    @Override 
    public void onCreate(SQLiteDatabase database) 
    { 
     String[] SqlStatements = 
     { 
     "CREATE TABLE TestTable (Id INTEGER PRIMARY KEY, test varchar(255) NOT null)" 
     }; 

     for (int i = 0; i < SqlStatements.length; i++) 
     database.execSQL(SqlStatements[i]); 
    } 

    @Override 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
    { 

    } 
    } 

Изменить свою реализацию:

DBHelper db = new DBHelper(getApplicationContext()); 
//here CredentialDb is my database. you can create your db object. 
File exportDir = new File(Environment.getExternalStorageDirectory(), ""); 

if (!exportDir.exists()) 
{ 
    exportDir.mkdirs(); 
} 


try 
{ 

    File file = new File(exportDir, "csvfilename.csv"); 
    file .setReadable(true, false); 
    file .setWritable(true,false); 

    CSVWriter csvWrite = new CSVWriter(new FileWriter(file)); 
    SQLiteDatabase sql_db = db.getWritableDatabase(); 
    Cursor curCSV = sql_db.rawQuery("SELECT * FROM "+Database.DATABASE_TABLE,null); 
    csvWrite.writeNext(curCSV.getColumnNames()); 

    while(curCSV.moveToNext()) 
    { 
     //Which column you want to export you can add over here... 
     String arrStr[] ={curCSV.getString(0),curCSV.getString(1), curCSV.getString(2)}; 
     csvWrite.writeNext(arrStr); 

     csvWrite.close(); 
     curCSV.close(); 
    } 
} 
catch(Exception sqlEx) 
{ 
    Log.e("Error:", sqlEx.getMessage(), sqlEx); 
} 
Смежные вопросы