android SQLite 优化(三)使用事务 优化 insert

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010136741/article/details/41010533

SQLite 没插入一条数据默认创建一次事务

通过显示调用事务,可以提高SQLite操作的性能


        	String[] sCheeseNames = {"a","b","a","b","a","b","a","b"};
        	String[] sCheeseOrigins = {"aa","bb","aa","bb","aa","bb","aa","bb"};
        	SQLiteDatabase db = SQLiteDatabase.create(null);
        	try {

            	db.beginTransaction();//开启事务
            	
            	SQLiteStatement stmt = db.compileStatement("INSERT INTO cheese VALUES(?,?)");  
                int i = 0;  
                for (String name:sCheeseNames){  
                    String origion = sCheeseOrigins[i++];  
                    stmt.clearBindings();  
                    stmt.bindString(1, name);  
                    stmt.bindString(2, origion);  
                    stmt.executeInsert();  
                }  
            	db.setTransactionSuccessful();//事务提交
			} catch (Exception e) {
				// TODO: handle exception
			}finally{
				db.endTransaction();//事务回滚
				
			}

当数据库做持久存储时,特别是存储在外部sd卡时,更应该采用一次性事务!

猜你喜欢

转载自blog.csdn.net/u010136741/article/details/41010533
今日推荐