1. 批量导入
添加事务处理,把5000条插入作为一个事务
dataBase.beginTransaction(); //手动设置开始事务
//数据插入操作循环
dataBase.setTransactionSuccessful(); //设置事务处理成功,不设置会自动回滚不提交
dataBase.endTransaction(); //处理完成
2. 数据库拷贝
操作方法:
1)把原数据库包括在项目源码的 res/raw 目录下.
2)创建一个类来控制database.
如下:
public class DatabaseManager{
private final int BUFFER_SIZE = 400000;
public static final String DB_NAME = "myDatabase.db"; //保存的数据库文件名
public static final String PACKAGE_NAME = "com.android.ImportDBTest";//包名
public static final String DB_PATH = "/data"
+ Environment.getDataDirectory().getAbsolutePath() + "/"
+ PACKAGE_NAME; //在手机里存放数据库的位置
private SQLiteDatabase database;
private Context context;
DBManager(Context context) {
this.context = context;
}
public void openDatabase() {
this.database = this.openDatabase(DB_PATH + "/" + DB_NAME);
}
private SQLiteDatabase openDatabase(String dbfile) {
try {
if (!(new File(dbfile).exists())) { //判断数据库文件是否存在,若不存在则执行导入,否则直接打开数据库
InputStream is = this.context.getResources().openRawResource(
R.raw.myDatabase); //欲导入的数据库
FileOutputStream fos = new FileOutputStream(dbfile);
byte[] buffer = new byte[BUFFER_SIZE];
int count = 0;
while ((count = is.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
fos.close();
is.close();
}
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile,
null);
return db;
} catch (FileNotFoundException e) {
Log.e("Database", "File not found");
e.printStackTrace();
} catch (IOException e) {
Log.e("Database", "IO exception");
e.printStackTrace();
}
return null;
}