我使用此例程将 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.open() 与 dbAdapter.close() 配对。另外,不要忘记关闭您打开的每个游标。
注意: csvValues 是每个 SQLite 行中返回的列的串联。对于 SQLite 游标中返回的每一行,csvValues 将作为一行写入 CSV 表中。