在Android中对SQLite数据库的操作,涉及以下几个方面:
1、确认数据库文件,即.db文件;
2、通过android.database.sqlite. SQLiteDatabase类的openOrCreateDatabase()方法打开数据库;
3、数据库操作:
A、开始事务: SQLiteDatabase.beginTransaction();
B、执行sql语句;
C、结束事务: SQLiteDatabase.endTransaction();
具体代码可参考如下:
- static boolean installDefaultSitesToDB(Context cxt) {
- // 确认目标数据库文件
- File path = cxt.getDir("databases", Context.MODE_WORLD_WRITEABLE);
- path = new File(path, "db_name.db");
- SQLiteDatabase db = null;
- try {
- // 打开数据库
- db = openDB(path.getAbsolutePath());
- if (db == null) {
- //Log.e("tag", "open db_name.db ERROR~");
- return false;
- }
- db.beginTransaction();//开始事务
- boolean bool = doInstallData(db);//执行sql语句,插入数据
- //设置事务标志
- if (bool) {
- db.setTransactionSuccessful();// 设置事务标志
- } else {
- //Log.w("tag", "doInstall.DEFAULT_SITES Fail~!");
- }
- return bool;
- } finally {
- if (db != null) {
- //结束事务
- if (db.inTransaction()) {db.endTransaction();}
- db.close();
- }
- }
- }
- private static SQLiteDatabase openDB(String file) {
- try {
- //SQLiteDatabase.openOrCreateDatabase(file, null);
- int flag = SQLiteDatabase.OPEN_READWRITE;
- flag = flag | SQLiteDatabase.CREATE_IF_NECESSARY;
- flag = flag | SQLiteDatabase.NO_LOCALIZED_COLLATORS;
- SQLiteDatabase db = SQLiteDatabase.openDatabase(file, null, flag);
- return db;
- } catch (Throwable e) {
- //Log.e("tag","openDatabase error:" + e.getMessage());
- return null;
- }
- }
- //
- private static boolean doInstallData(SQLiteDatabase db) {
- try {
- //create table
- String sql = "CREATE TABLE IF NOT EXISTS Permissions (origin TEXT UNIQUE NOT NULL, allow INTEGER NOT NULL)";
- db.execSQL(sql);
- ContentValues cv = new ContentValues();
- for (String site : DEFAULT_SITES) {
- cv.clear();
- cv.put("origin", site);
- cv.put("allow", 1);
- long ret = db.insertOrThrow("Permissions", null, cv);
- Log.d("tag", "db.insert.RET:" + ret);
- }
- return true;
- } catch (SQLException se) {
- String msg = "doInstall.error:[%s].%s";
- Log.d("tag",String.format(msg, se.getClass(),se.getMessage()));
- return false;
- }
- }