下面是我目前正在使用的代码,但我正在寻找一种加快插入速度的方法,而且我第一次插入了 100 多行...有什么想法吗?
public class SQLiteAdapter {
private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;
private Context context;
public SQLiteAdapter(Context c){
context = c;
}
public long insert(String empId, String name......)
{
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_EMP_ID, empId);
.....................
.....................
.....................
return sqLiteDatabase.insert(KEY_TABLE, null, contentValues);
}
public void InsertReciters()
{
//currently, this is how i am doing, how can i speed up inserting the rows in to db?
//i have 100+ rows ..........
this.insert("ac123", ................);
this.insert("ac133", ................);
this.insert("ac143", ................);
this.insert("ac153", ................);
this.insert("ac163", ................);
.................
.................
}
}
最佳答案
建议您通过事务插入大量数据。
代码格式如下:
List<String[]> hugeData=new ArrayList<String[]>();
try{
sqLiteDatabase.beginTransaction();
//insert huge data
//get pre-compiled SQLiteStatement object
SQLiteStatement statement=sqLiteDatabase.compileStatement("insert into tablename(..) value (?,?)")
for(String[] row:hugeData){
statement.bindString(1,row[0]);
//......
statement.execute();
}
sqLiteDatabase.setTransactionSuccessful();
}finally{
sqLiteDatabase..endTransaction();
}
--------------------已编辑--------------------
public class SQLiteAdapter {
private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;
private Context context;
List<String[]> insertData=null;
public SQLiteAdapter(Context c){
context = c;
}
public SQLiteAdapter(Context c,List<String[]> _insertData){
this(c);
insertData=_insertData;
}
public long insert(String empId, String name......)
{
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_EMP_ID, empId);
.....................
.....................
.....................
return sqLiteDatabase.insert(KEY_TABLE, null, contentValues);
}
public void InsertReciters()
{
//currently, this is how i am doing, how can i speed up inserting the rows in to db?
//i have 100+ rows ..........
this.insert("ac123", ................);
this.insert("ac133", ................);
this.insert("ac143", ................);
this.insert("ac153", ................);
this.insert("ac163", ................);
.................
.................
}
public void InsertBatchData()
{
try{
sqLiteDatabase.beginTransaction();
//insert huge data
//get pre-compiled SQLiteStatement object
SQLiteStatement statement=sqLiteDatabase.compileStatement("insert into tablename(..) value (?,?)")
for(String[] row:hugeData){
statement.bindString(1,row[0]);
//......
statement.execute();
}
sqLiteDatabase.setTransactionSuccessful();
}finally{
sqLiteDatabase..endTransaction();
}
}
}
关于Android:使用 SQLite 插入批处理数据(一次),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9882830/