使用 SQLiteOpenHelper 到 SQL 中的 运行 语句

Using SQLiteOpenHelper to run statements from SQL

当我尝试通过将相关 SQL 语句复制到包含 SQLiteOpenHelper 必须 SQL 语句的 String 变量中来插入我的数据的一小部分时=25=],一切正常。这是我的查询:

String POPULATE_TABLE =
            "INSERT INTO `en_sahih` (`indexID`, `chapterNo`, `verseNo`, `verseText`) VALUES\n" +
            "(1, 1, 1, 'This is verse 1'),\n" +
            "(2, 1, 2, 'This is verse 2'),\n" +
            "(3, 1, 3, 'This is verse 3'),\n" +
            "(4, 1, 4, 'This is verse 4'),\n" +
            "(5, 1, 5, 'This is verse 5'),\n" +
            "(6, 1, 6, 'This is verse 6'),\n" +
            "(7, 1, 7, 'This is verse 7');";
    db.execSQL(POPULATE_TABLE);

但是当我将整个 6k 记录复制到字符串中时,这可能不是解决此问题的理想方法,Android studio 告诉我 String 太长了。如何轻松获取 SQL 语句形式的数据并将其放入 .sql 文件并在我在我的应用程序中设置的新数据库中执行它们。有关如何执行此操作的任何建议?

您最好的选择是使用 XML 或类似 CSV 的内容。您可以轻松地放入 table 中的所有数据,用适当的标签对其进行排列,然后访问以检索数据并插入到您的其他数据库中。如果您不确定 XML 是什么样子:

<parent attribute="something">
    <child attribute="something">
        <!-- More tags or data here //-->
    </child>
</parent>

如果您不确定如何实现这一点,我建议您查看 页面,其中有一个关于将数据库导出到 XML 文件的问题。看你怎么样了。

  1. 将记录保存在文本文件中(通过用 crlf 分隔每条记录)

     // records.txt
     1, 1, 1, 'This is verse 1'
     2, 1, 2, 'This is verse 2'
    
  2. 然后您可以使用某些 Reader 实现从文件中读取记录(例如 BufferedReader)

    file -> file input stream -> reader 
    

    How can I read a text file in Android?

     // create the file class object pointing to text file 
     File file = new File(some_path,"records.txt");
    
     // initialize reader class object providing file object
     BufferedReader br = new BufferedReader(new FileReader(file));
    
  3. 使用 while 循环处理数据 -> Reader.readline() 方法

     while ((line = Reader.readLine()) != null) {
    
         // a/ do insert 
         // b/ store data in some prim array 
         //    or via some list implementation (`ArrayList<String>`) 
         // then use insert or bulk
    
     }
    

I love the comprehensiveness of this answer @ceph3us Thanks a lot. However, there are two things: 1. doing 6k inserts using this approach might slow things down, how do I deal with that? and 2. Since I will be inserting using multiple copies of this file (different languages), having text files as well as the database itself is going to create redundancy and double the mount of space my app takes up on a device. Is it possible to programmatically delete a text file once I'm done with the inserts?

  1. 第一次请阅读:

    插入 6k 条记录可能需要 几秒钟 :)

    https://www.sqlite.org/faq.html#q19

  2. 二次使用

     File.delete();
    

    RandomAccessFile.setLength(0);
    

来自作者:

您的应用程序是否使用网络通信??

如果 - 考虑使用一些虚拟主机帐户或 vps 作为应用数据的外部来源 - 那么 分布式大小将是小。 - 你也可以保持数据不过时(某种更新是在服务器端完成的 - 在你的情况下要插入记录 - 你减少了在客户端更新应用程序的需要) -基本上移动到 server/client 应用程序