我试图从我的sqlite数据库中获取数据并将其写入csv文件并在写完文件时通过电子邮件发送信息。在数据库中只有一个包含3列的表。我有DBAdapter和一个具有Button的类用户必须按才能导出数据。
以下是我尝试过的代码 Exportdata.java
try {
root = Environment.getExternalStorageDirectory();
Log.i(TAG,"path.." +root.getAbsolutePath());
//check sdcard permission
if (root.canWrite()) {
File fileDir = new File(root.getAbsolutePath()+"/fun/");
fileDir.mkdirs();
// Log.d("DATABASE", db.getAllBYname());
File file= new File(fileDir, "itisfun.csv");
FileWriter filewriter = new FileWriter(file);
BufferedWriter out = new BufferedWriter(filewriter);
out.write("I m enjoying......dude..............." );
out.close();
}
} catch (IOException e) {
Log.e("ERROR:---", "Could not write file to SDCard" + e.getMessage());
}
这段代码确实在SD卡中创建了文件,但问题是我不能把它带到sqlite数据库数据并将其写入文件中,如code.im上所示卡住请帮我举例或用右边编辑我的代码溶液
答案 0 :(得分:10)
我使用此例程将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表中写为一行。