Android数据库小技巧
一、执行SQL
相对于封装过的ContentProvider,使用原生SQL执行效率高,所以建议使用rawQuery、execSQL。
二、代理事务
假设继承SQLiteOpenHelper的数据库操作类为DatabaseHelper。当它有比较多的方法都需要事务操作时,可以提取这些方法为一个接口,如ITransactionHandler,之后让DatabaseHelper实现。这样即可通过代理来统一完成事务操作!
-
-
-
-
-
-
-
-
-
-
public class TransactionHandler implements InvocationHandler {
-
-
private static final String TAG = "TransactionHandler";
-
public static final boolean LOGD = true;
-
-
-
private DatabaseHelper mDatabaseHelper;
-
-
public TransactionHandler(DatabaseHelper helper) {
-
this.mDatabaseHelper = helper;
- }
-
-
-
public static Object newProxyInstance(DatabaseHelper helper) {
-
-
return Proxy.newProxyInstance(helper.getClass().getClassLoader(),
-
helper.getClass().getInterfaces(), new TransactionHandler(
- helper));
- }
-
-
-
@Override
-
public Object invoke(Object proxy, Method method, Object[] args)
-
throws Throwable {
-
long start = System.currentTimeMillis();
-
Object result = null;
-
SQLiteDatabase mDatabase = mDatabaseHelper.getWritableDatabase();
-
mDatabase.beginTransaction();
-
try {
-
- result = method.invoke(mDatabaseHelper, args);
-
- mDatabase.setTransactionSuccessful();
-
} catch (Exception e) {
- e.printStackTrace();
-
-
-
-
-
-
result = false;
-
} finally {
-
mDatabase.endTransaction();
- }
-
long end = System.currentTimeMillis();
-
if (LOGD)
-
Log.d(TAG, "==" + method.getName() + " method lasts "
-
+ (end - start) + "ms==");
-
return result;
- }
-
- }
三、文件SQL
执行一个SQL文件,以初始化数据等。可以把sql文件放在res/raw目录内。sql文注释方式,简易为“—”开头的行或“/*”“*/”开始的两行中间。
- public class SqlUtil {
-
-
private final String commentPrefix = "--";
-
private final String prefix = "/*";
-
private final String suffix = "*/";
-
private boolean isComment = false;
-
-
private Context mContext;
-
private SQLiteDatabase db;
-
-
public SqlUtil(Context context, SQLiteDatabase db) {
- mContext = context;
-
this.db = db;
- }
-
-
-
public void execute(int rawId) {
-
BufferedReader reader = null;
-
try {
- InputStream is = mContext.getResources().openRawResource(rawId);
-
reader = new BufferedReader(new InputStreamReader(is));
-
for (String s; (s = reader.readLine()) != null;) {
-
if (s.startsWith(commentPrefix)) {
-
continue;
- }
-
if (s.startsWith(prefix)) {
-
isComment = true;
-
continue;
- }
-
if (s.startsWith(suffix)) {
-
isComment = false;
-
continue;
- }
-
if (isComment) {
-
continue;
- }
- db.execSQL(s);
- }
-
} catch (IOException e) {
- e.printStackTrace();
-
} finally {
-
try {
-
if (null != reader) {
- reader.close();
- }
-
} catch (IOException e) {
- }
- }
- }
-
- }
四、后记
其他的话,暂时应该没什么了…
本文转自winorlose2000 51CTO博客,原文链接:http://blog.51cto.com/vaero/900853,如需转载请自行联系原作者