【发布时间】:2016-07-11 16:44:02
【问题描述】:
我有一种方法可以逐行从文件中读取数据并在逗号之间取值,然后将该值放入 INSERT 查询中。以这种方式保存的文件中的数据:
–,08:10,–,20:20,08:15,08:16,20:26,20:27,08:20,08:21,20:31,20:32,08:30,08:31,20:40,20:41,08:37,08:38,20:46
20:47,08:48,08:50,20:56,20:57,09:00,09:01,21:07,21:08
08:53,–,17:43,09:01,09:03,09:13,09:15,18:02,18:04,–,–,09:19,09:25
这是我的实际代码:
public void insertTime(SQLiteDatabase database, String table) throws FileNotFoundException {
BufferedReader br = null;
String line;
try {
int j = 0;
br = new BufferedReader(new InputStreamReader(context.getAssets().open("time.txt")));
database.beginTransaction();
while ((line = br.readLine()) != null) {
j++;
String query = "INSERT INTO "+table+""+j+" (arrival, departure) VALUES (?,?)";
SQLiteStatement statement = database.compileStatement(query);
// use comma as separator
String[] time = line.split(",");
for(int i = 1; i < time.length; i+=2) {
statement.bindString(1,time[i-1]);//arrival
statement.bindString(2,time[i]);//departure
statement.executeInsert();
statement.clearBindings();
}
}
database.setTransactionSuccessful();
database.endTransaction();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
问题是数据插入速度很慢,尽管我使用了SQLiteStatement 和transactions。例如,当我插入 69000 行时,大约需要 65,929 秒。
为了提高插入速度,我需要对代码进行哪些更改?
更新
好的,我已经简化了我的代码,我摆脱了 BufferedReader,现在它看起来像这样
public void insertTime(SQLiteDatabase database) throws FileNotFoundException {
database.beginTransaction();
int r = 0;
while (r < 122) {
r++;
String query = "INSERT INTO table_1 (arrival, departure) VALUES (?,?)";
SQLiteStatement statement = database.compileStatement(query);
for(int i = 1; i < 1100; i++) {
statement.bindString(1,i+"");//arrival
statement.bindString(2,i+"");//departure
statement.executeInsert();
statement.clearBindings();
}
}
database.setTransactionSuccessful();
database.endTransaction();
}
但是插入数据还是那么长,超过2分钟。您对如何提高我的第二个示例的速度有任何想法吗?
【问题讨论】:
-
所有代码都写在 C 上,如果我使用 java,它对我有什么帮助?
-
sqlite 无处不在。在那篇文章中唯一的 C 是如何执行 sqlite 命令。 sql语句在任何介质中都是一样的。
-
是的,但我几乎都像那里所说的那样做了。我使用了事务和准备好的语句,但速度仍然很慢。
标签: android performance sqlite