简体   繁体   中英

How to export data from SQlite to CSV or Excel or just anything?

Doing research on how to export a database from SQLite, I already found the following code but was not able to make it work for me.

myDbAdapter.java:

public static void exportDB(Context context) {
    String databasePath = context.getDatabasePath(myDbHelper.DATABASE_NAME).getPath();
    String inFileName = databasePath;
    try {
        File dbFile = new File(inFileName);
        FileInputStream fis = new FileInputStream(dbFile);

        String outFileName = Environment.getExternalStorageDirectory() + "/" + myDbHelper.DATABASE_NAME;

        OutputStream output = new FileOutputStream(outFileName);

        byte[] buffer = new byte[1024];
        int length;
        while ((length = fis.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
        //Close the streams
        output.flush();
        output.close();
        fis.close();
    } catch (Exception e) {
        Toast.makeText(context, "Export Failed", Toast.LENGTH_SHORT).show();
    }
}

MainActivity.java:

public void export(View view){
    helper.exportDB(getApplicationContext());
}

public static void main(String[] args){}

When I press the Export Button it says "Export Failed". Before I added the void main there was an error telling me that it is needed but I have no idea what to put into it. Additionally I don't think Environment.getExternalStorageDirectory() is the right way to find the directory since there is no SDCard in my Tablet. Any help appreciated!

You can setup any destination for output file by yourself

psThis code should not export anything. It just rewrite the same data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM