gpt4 book ai didi

android - 将数据库 .db 文件转换为 .csv

转载 作者:IT王子 更新时间:2023-10-29 06:27:55 25 4
gpt4 key购买 nike

我正在开发一个应用程序,我在其中使用数据库并将扩展名为 .db 的数据库文件存储到 sdcard 中。现在我想将此“db 文件转换为 .csv”,以便用户可以打开该 .csv文件并可以轻松查看其所有数据...

最佳答案

嘿,我得到了我自己问题的答案:我下载了一个 OpenCSV 库并将 opencsv.jar 文件添加到我的应用程序和以下代码中:

class ExportDatabaseCSVTask extends AsyncTask<String, Void, Boolean>{
private final ProgressDialog dialog = new ProgressDialog(MyDatabaseActivity.this);

// can use UI thread here
@Override
protected void onPreExecute(){
this.dialog.setMessage("Exporting database...");
this.dialog.show();
}


// automatically done on worker thread (separate from UI thread)
protected Boolean doInBackground(final String... args){
File dbFile=getDatabasePath("mydb.db");
// DbClass DBob = new DbClass(MyDatabaseActivity.this);
File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File file = new File(exportDir, "excerDB.csv");
try {
file.createNewFile();
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
//SQLiteDatabase db = DBob.getReadableDatabase();
Cursor curCSV=mydb.rawQuery("select * from " + TableName_ans,null);
// Cursor curCSV = db.rawQuery("SELECT * FROM table_ans12",null);
csvWrite.writeNext(curCSV.getColumnNames());

while(curCSV.moveToNext()){
String arrStr[] ={curCSV.getString(0),curCSV.getString(1)};
/*curCSV.getString(2),curCSV.getString(3),curCSV.getString(4)*/
csvWrite.writeNext(arrStr);
}

csvWrite.close();
curCSV.close();
return true;

} catch(SQLException sqlEx) {
Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
return false;
} catch (IOException e) {
Log.e("MainActivity", e.getMessage(), e);
return false;
}
}

// can use UI thread here
@Override
protected void onPostExecute(final Boolean success) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
if (success) {
Toast.makeText(MyDatabaseActivity.this, "Export successful!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MyDatabaseActivity.this, "Export failed", Toast.LENGTH_SHORT).show();
}
}
}

关于android - 将数据库 .db 文件转换为 .csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8665057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com