简体   繁体   English

如何将 excel 文件导入房间 sqlite 数据库并管理冲突?

[英]How to import and manage conflicts an excel file into room sqlite database?

I want to import an excel file into my database designed with room library on android.我想将 excel 文件导入到我的数据库中,该数据库使用 android 上的房间库设计。 I can export the database using a library but for import i need to check items and handle conflicts but I don't know how.我可以使用库导出数据库,但对于导入,我需要检查项目并处理冲突,但我不知道如何。

It would be nice to look on the following articles.看看下面的文章会很好。 Article1 and article2 focuses on using room to import csv using room.第1 和第2条重点介绍使用room导入csv using room。

If you can use a different library, this is also helpful.如果您可以使用不同的库, 也很有帮助。

I will advise to break this functionality into two tasks.我建议将此功能分为两个任务。

  1. Extract data from CSV/Excel file从 CSV/Excel 文件中提取数据
  2. Put that data into the database将这些数据放入数据库

1 To extract data from CSV/Excel File, you can use the following code. 1 要从 CSV/Excel 文件中提取数据,您可以使用以下代码。

    CSVReader csvReader = new CSVReader(new FileReader(Environment.getExternalStorageDirectory() + "/" + TableName));
String[] nextLine;
int count = 0;
StringBuilder columns = new StringBuilder();
StringBuilder value = new StringBuilder();
 
while ((nextLine = csvReader.readNext()) != null) {
      // nextLine[] is an array of values from the line
         for (int i = 0; i < nextLine.length - 1; i++) {
             if (count == 0) {
                 if (i == nextLine.length - 2)
                     columns.append(nextLine[i]);
                 else
                     columns.append(nextLine[i]).append(",");
             } else {
                 if (i == nextLine.length - 2)
                    value.append("'").append(nextLine[i]).append("'");
                 else
                    value.append("'").append(nextLine[i]).append("',");
             }
        }
  1. To put the extracted data into the database you can use the following code.要将提取的数据放入数据库,您可以使用以下代码。

Create a raw query function in your DAO.在您的 DAO 中创建一个原始查询 function。

@RawQuery  
Boolean insertDataRawFormat(SupportSQLiteQuery query);

Using that query put the data into the Database使用该查询将数据放入数据库

SimpleSQLiteQuery query = new SimpleSQLiteQuery("Insert INTO " + tableName + " (" + columns + ") " + "values(" + value + ")",
           new Object[]{});
    getDb().cashDrawerDao().insertDataRawFormat(query);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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