我用這個程序來SQLite數據庫轉儲到CSV格式的SD卡上的文件:
private Boolean backupDatabaseCSV(String outFileName) {
MyLog.d(TAG, "backupDatabaseCSV");
Boolean returnCode = false;
int i = 0;
String csvHeader = "";
String csvValues = "";
for (i = 0; i < GC.CURCOND_COLUMN_NAMES.length; i++) {
if (csvHeader.length() > 0) {
csvHeader += ",";
}
csvHeader += "\"" + GC.CURCOND_COLUMN_NAMES[i] + "\"";
}
csvHeader += "\n";
MyLog.d(TAG, "header=" + csvHeader);
dbAdapter.open();
try {
File outFile = new File(outFileName);
FileWriter fileWriter = new FileWriter(outFile);
BufferedWriter out = new BufferedWriter(fileWriter);
Cursor cursor = dbAdapter.getAllRows();
if (cursor != null) {
out.write(csvHeader);
while (cursor.moveToNext()) {
csvValues = Long.toString(cursor.getLong(0)) + ",";
csvValues += Double.toString(cursor.getDouble(1))
+ ",";
csvValues += Double.toString(cursor.getDouble(2))
+ ",";
csvValues += "\"" + cursor.getString(3) + "\",";
csvValues += Double.toString(cursor.getDouble(4))
+ ",";
csvValues += Double.toString(cursor.getDouble(5))
+ ",";
csvValues += "\"" + cursor.getString(6) + "\",";
csvValues += Double.toString(cursor.getDouble(7))
+ ",";
csvValues += Double.toString(cursor.getDouble(8))
+ ",";
csvValues += Double.toString(cursor.getDouble(9))
+ "\n";
out.write(csvValues);
}
cursor.close();
}
out.close();
returnCode = true;
} catch (IOException e) {
returnCode = false;
MyLog.d(TAG, "IOException: " + e.getMessage());
}
dbAdapter.close();
return returnCode;
}
GC是我的全局常量類,除其他外包含表的列名。列名稱用於製作CSV文件中的標題行。 getAllRows位於數據庫適配器中,並返回表中的所有行。 while轉儲所有返回的行。長整型值用逗號分隔,文本值用逗號分隔。 MyLog.d在測試模式下執行Log.d,並且在生產模式下不執行任何操作。在將對DBAdapter是在函數的外部定義爲一個全局變量:
DatabaseAdapter dbAdapter = null;
它在的onCreate初始化爲:
dbAdapter = new DatabaseAdapter(getApplicationContext());
在將對DBAdapter在多個功能中使用的活性。如果您全局定義數據庫適配器,請確保在每次使用dbAdapter.close()時將每個dbAdapter.open()配對。另外,不要忘記關閉你打開的每一個光標。
注意:csvValues是每個SQLite行中返回的列的並置。對於在SQLite遊標中返回的每一行,csvValues在CSV表中作爲一行寫入。