我有一个 SQLite 数据库,我需要定期删除其中的记录。从性能角度来看,最好的方法是什么?我有一系列独特的 PK ID。我想出了两种方法:
使用准备好的语句
int[] ids = {1,2,3,4,5}; //example only, will be built elsewhere
Database db = null;
try {
db = DataConnection.getInstance(); //my class to get the connection instance
db.beginTransaction();
Statement st = db.createStatement("DELETE FROM myTable WHERE id = ?");
st.prepare();
for (int i=0;i<ids.length;i++) {
st.bind(1, ids[i]);
st.execute();
st.reset();
}
db.commitTransaction();
} catch (FileIOException e) {
e.printStackTrace();
} catch (DatabaseException e) {
e.printStackTrace();
}
或者使用“in”关键字
int[] ids = {1,2,3,4,5}; //example only, will be built elsewhere
Database db = null;
try {
db = DataConnection.getInstance();
//Util.JoinArray(int[] ids,char delim, char prepend, char postpend) returns a String of the ids separated by delim with prepend at the front and postpend at the end
Statement st = db.createStatement("DELETE FROM myTable WHERE id IN " + Util.joinArray(ids,',','(',')'));
st.prepare();
} catch (FileIOException e) {
e.printStackTrace();
} catch (DatabaseException e) {
e.printStackTrace();
}
最佳答案
理想的方法是两者的结合:所有 ID 的准备语句。
因此,请避免 SQL 注入(inject)并使用这样的方法(以伪代码形式):
query = "DELETE FROM myTable WHERE id IN (";
for (int i = 0; i < ids.count; i++)
query.Append("?,");
query.DropLast(); //Remove the last comma
query.Append(")");
st = db.createStatement(query);
st.prepare();
for (int i = 0; i < ids.count; i++)
st.bind(i+1, ids[i]);
就性能而言,这可能会更好,因为数据库将在所有删除后重新平衡索引。不过,在事务中工作并在所有单独删除后提交一次本质上是相同的。我建议的方法更加安全。
正如 SO 上经常讨论的那样,SQLite 性能因各种标准而异,即结构、行数、页面大小等。SQLite 不存在通用的“在所有情况下都更快”的方法。您的里程会有所不同。
关于sqlite - 黑莓 SQLite 批量删除最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8934181/