导出SQLite数据库到csv文件在android [英] Exporting SQLite Database to csv file in android

查看:353
本文介绍了导出SQLite数据库到csv文件在android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图导出SQLite数据到SD卡在Android中作为一个目录上的CSV文件。



所以我试过这个方法下面,显然它只显示此文字列印出来:



数据库的第一个表

日期,项目,金额,货币



在我的DBHelper.java中,我定义了如下函数:

  public boolean exportDatabase(){
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT,Locale.getDefault());

/ **首先我们检查设备的外部存储设备是否可用于写入。
*请记住,外部存储不一定是sd卡。通常是
*设备存储。
* /
String state = Environment.getExternalStorageState();
if(!Environment.MEDIA_MOUNTED.equals(state)){
return false;
}
else {
//我们使用下载目录保存我们的.csv文件。
文件exportDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
if(!exportDir.exists())
{
exportDir.mkdirs();
}

文件文件;
PrintWriter printWriter = null;
try
{
file = new File(exportDir,MyCSVFile.csv);
file.createNewFile();
printWriter = new PrintWriter(new FileWriter(file));

/ **这是我们的数据库连接器类,它从数据库读取数据。
*为简洁起见,省略了这个类的代码。
* /
SQLiteDatabase db = this.getReadableDatabase(); //打开读取数据库

/ **让我们读取数据库的第一个表。
* getFirstTable()是我们的DBCOurDatabaseConnector类中的一个方法,它检索包含表的所有记录(所有字段)的游标
*。
*为简洁起见,省略了这个类的代码。
* /
Cursor curCSV = db.rawQuery(select * from contacts,null);
//在.csv文件中写入表的名称和列的名称(逗号分隔值)。
printWriter.println(FIRST TABLE OF THE DATABASE);
printWriter.println(DATE,ITEM,AMOUNT,CURRENCY);
while(curCSV.moveToNext())
{
Long date = curCSV.getLong(curCSV.getColumnIndex(date));
String title = curCSV.getString(curCSV.getColumnIndex(title));
Float amount = curCSV.getFloat(curCSV.getColumnIndex(amount));
String description = curCSV.getString(curCSV.getColumnIndex(description));

/ **创建要在.csv文件中写入的行。
*我们需要一个字符串,其中的值以逗号分隔。
*字段日期(Long)以可读文本格式化。金额字段
*转换为字符串。
* /
String record = df.format(new Date(date))+,+ title +,+ amount +,+ description;
printWriter.println(record); //在.csv文件中写入记录
}

curCSV.close();
db.close();
}

catch(Exception exc){
//如果有任何异常,返回false
return false;
}
finally {
if(printWriter!= null)printWriter.close();
}

//如果没有错误,返回true。
return true;
}
}
}

/ p>

  public static final String DATABASE_NAME =MyDBName.db; 
public static final String CONTACTS_TABLE_NAME =contacts;
public static final String CONTACTS_COLUMN_ID =id;
public static final String CONTACTS_COLUMN_TITLE =title;
public static final String CONTACTS_COLUMN_AMOUNT =amount;
public static final String CONTACTS_COLUMN_DESC =description;如果您需要更多代码,请告诉我。



解决方案

感谢您的建议。 =jsdata-hide =false>

  private void exportDB ){File dbFile = getDatabasePath(MyDBName.db); DBHelper dbhelper = new DBHelper(getApplicationContext());文件exportDir = new File(Environment.getExternalStorageDirectory(),); if(!exportDir.exists()){exportDir.mkdirs(); }文件file =新文件(exportDir,csvname.csv); try {file.createNewFile(); CSVWriter csvWrite = new CSVWriter(new FileWriter(file)); SQLiteDatabase db = dbhelper.getReadableDatabase(); Cursor curCSV = db.rawQuery(SELECT * FROM contacts,null); csvWrite.writeNext(curCSV.getColumnNames()); while(curCSV.moveToNext()){//你要显示哪一列String arrStr [] = {curCSV.getString(0),curCSV.getString(1),curCSV.getString(2)}; csvWrite.writeNext(arrStr); } csvWrite.close(); curCSV.close(); } catch(Exception sqlEx){Log.e(MainActivity,sqlEx.getMessage(),sqlEx); }  


I am trying to export SQLite data to SD card in android as a CSV file on a directory.

So i have tried this method below and apparently it only shows this text printed out:

FIRST TABLE OF THE DATABASE
DATE,ITEM,AMOUNT,CURRENCY

In my DBHelper.java i have defined the function as follows:

public boolean exportDatabase() {
        DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());

        /**First of all we check if the external storage of the device is available for writing.
         * Remember that the external storage is not necessarily the sd card. Very often it is
         * the device storage.
         */
        String state = Environment.getExternalStorageState();
        if (!Environment.MEDIA_MOUNTED.equals(state)) {
            return false;
        }
        else {
            //We use the Download directory for saving our .csv file.
            File exportDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            if (!exportDir.exists())
            {
                exportDir.mkdirs();
            }

            File file;
            PrintWriter printWriter = null;
            try
            {
                file = new File(exportDir, "MyCSVFile.csv");
                file.createNewFile();
                printWriter = new PrintWriter(new FileWriter(file));

                /**This is our database connector class that reads the data from the database.
                 * The code of this class is omitted for brevity.
                 */
                SQLiteDatabase db = this.getReadableDatabase(); //open the database for reading

                /**Let's read the first table of the database.
                 * getFirstTable() is a method in our DBCOurDatabaseConnector class which retrieves a Cursor
                 * containing all records of the table (all fields).
                 * The code of this class is omitted for brevity.
                 */
                Cursor curCSV = db.rawQuery("select * from contacts", null);
                //Write the name of the table and the name of the columns (comma separated values) in the .csv file.
                printWriter.println("FIRST TABLE OF THE DATABASE");
                printWriter.println("DATE,ITEM,AMOUNT,CURRENCY");
                while(curCSV.moveToNext())
                {
                    Long date = curCSV.getLong(curCSV.getColumnIndex("date"));
                    String title = curCSV.getString(curCSV.getColumnIndex("title"));
                    Float amount = curCSV.getFloat(curCSV.getColumnIndex("amount"));
                    String description = curCSV.getString(curCSV.getColumnIndex("description"));

                    /**Create the line to write in the .csv file.
                     * We need a String where values are comma separated.
                     * The field date (Long) is formatted in a readable text. The amount field
                     * is converted into String.
                     */
                    String record = df.format(new Date(date)) + "," + title + "," + amount + "," + description;
                    printWriter.println(record); //write the record in the .csv file
                }

                curCSV.close();
                db.close();
            }

            catch(Exception exc) {
                //if there are any exceptions, return false
                return false;
            }
            finally {
                if(printWriter != null) printWriter.close();
            }

            //If there are no errors, return true.
            return true;
        }
    }
}

And my columns are:

 public static final String DATABASE_NAME = "MyDBName.db";
 public static final String CONTACTS_TABLE_NAME = "contacts";
 public static final String CONTACTS_COLUMN_ID = "id";
 public static final String CONTACTS_COLUMN_TITLE = "title";
 public static final String CONTACTS_COLUMN_AMOUNT = "amount";
 public static final String CONTACTS_COLUMN_DESC = "description";

Let me know if you need more code.

解决方案

Thanks for your suggestions guys which led me to this answer:

private void exportDB() {

        File dbFile=getDatabasePath("MyDBName.db");
        DBHelper dbhelper = new DBHelper(getApplicationContext());
        File exportDir = new File(Environment.getExternalStorageDirectory(), "");
        if (!exportDir.exists())
        {
            exportDir.mkdirs();
        }

        File file = new File(exportDir, "csvname.csv");
        try
        {
            file.createNewFile();
            CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
            SQLiteDatabase db = dbhelper.getReadableDatabase();
            Cursor curCSV = db.rawQuery("SELECT * FROM contacts",null);
            csvWrite.writeNext(curCSV.getColumnNames());
            while(curCSV.moveToNext())
            {
                //Which column you want to exprort
                String arrStr[] ={curCSV.getString(0),curCSV.getString(1), curCSV.getString(2)};
                csvWrite.writeNext(arrStr);
            }
            csvWrite.close();
            curCSV.close();
        }
        catch(Exception sqlEx)
        {
            Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
        }

这篇关于导出SQLite数据库到csv文件在android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆