简单的增删改查

数据库代码

public class DBHelper {
	public static final String DB_NAME = "opinion_db";
	public static final String TABLE_NANE = "opinion_table";
	public static final int VERSION = 3;

	public static SQLiteDatabase db;// 只创建一次

	private OpenHelper openHelper;
	private final Context context;

	public DBHelper(Context context) {
		this.context = context;
	}

	public void openDB() {
		if (db == null) {
			openHelper = new OpenHelper(context, DB_NAME, null, VERSION);
			db = openHelper.getWritableDatabase();
			System.out.println("create database!");
		}
	}

	// 插入
	public long insert(OpinionModal opinion) {
		return db.insert(TABLE_NANE, null, putVaule(opinion));
	}

	// 查询
	@SuppressWarnings("unchecked")
	public ArrayList getAll() {
		ArrayList list = new ArrayList();
		Cursor cursor = null;
		cursor = db.query(TABLE_NANE, new String[] { "_id", "opinion"},
				null, null, null, null, null);
		while (cursor.moveToNext()) {
			list.add(mapPut(cursor));
		}
		return list;
	}

	// 根据_id删除单个或多个
	public void delete(int _id) {
		db.delete(TABLE_NANE, "_id=?", new String[] { String.valueOf(_id) });
	}

	// 删除所有
	public void deleteAll() {
		db.delete(TABLE_NANE, null, null);
	}

	// 删除标记的数据
	public void deleteMarked(ArrayList<Integer> deleteId) {
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append("_id=");
		for (int i = 0; i < deleteId.size(); i++) {
			if (i != deleteId.size() - 1) {
				stringBuffer.append(deleteId.get(i) + " or _id=");
			} else {
				stringBuffer.append(deleteId.get(i));
			}
		}
		db.delete(TABLE_NANE, stringBuffer.toString(), null);
	}

	// 封装了Map的put方法
	private Map<String, Object> mapPut(Cursor cursor) {
		// TODO Auto-generated method stub
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("_id", cursor.getString(cursor.getColumnIndex("_id")));
		map.put("opinion", cursor.getString(cursor.getColumnIndex("opinion")));
		return map;
	}

	// 封装ContentValues的put方法
	public ContentValues putVaule(OpinionModal opinion) {
		ContentValues values = new ContentValues();
		values.put("opinion", opinion.opinion);
		return values;
	}

	class OpenHelper extends SQLiteOpenHelper {

		public OpenHelper(Context context, String name, CursorFactory factory,
				int version) {
			super(context, name, factory, version);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			String sql = "create table "+ TABLE_NANE+ "("+ "_id integer primary key autoincrement,opinion text"+ ")";
			db.execSQL(sql);
		}

		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			String sql = "drop table if exists" + DB_NAME;
			db.execSQL(sql);
			openHelper.onCreate(db);
		}

	}
}

 

你可能感兴趣的:(增删改查)