---恢復內容開始---
新做了一個小項目,多數地方用到數據庫操作,在此記錄。
android自帶sqlite,新建一個類繼承SQLiteOpenHelper,重寫oncreate,onupgrade代碼,如下。
public class SkbDbHelper extends SQLiteOpenHelper { // If you change the database schema, you must increment the database version. private static final String TEXT_TYPE = " TEXT"; private static final String COMMA_SEP = ","; private static final String TIMESQL_CREATE_ENTRIES = "CREATE TABLE " + TimeEntry.TABLE_NAME + " (" + TimeEntry._ID + " INTEGER PRIMARY KEY," + TimeEntry.COLUMN_TITLE + TEXT_TYPE + COMMA_SEP + TimeEntry.COLUMN_TIME + TEXT_TYPE + COMMA_SEP + TimeEntry.COLUMN_BODY + TEXT_TYPE + COMMA_SEP + TimeEntry.COLUMN_CLOSE + TEXT_TYPE + " )"; private static final String STUSSQL_CREATE_ENTRIES = "CREATE TABLE " + StudentsEntry.TABLE_NAME + " (" + StudentsEntry._ID + " INTEGER PRIMARY KEY," + StudentsEntry.COLUMN_KID + TEXT_TYPE + COMMA_SEP + StudentsEntry.COLUMN_NAME + TEXT_TYPE + COMMA_SEP + StudentsEntry.COLUMN_CANJIA + TEXT_TYPE + COMMA_SEP + StudentsEntry.COLUMN_WENTI + TEXT_TYPE + COMMA_SEP + StudentsEntry.COLUMN_CLASS + TEXT_TYPE + " )"; private static final String BODYSQL_CREATE_ENTRIES = "CREATE TABLE " + BodyEntry.TABLE_NAME + " (" + BodyEntry._ID + " INTEGER PRIMARY KEY," + BodyEntry.COLUMN_NAME + TEXT_TYPE + COMMA_SEP + BodyEntry.COLUMN_CLASS + TEXT_TYPE + COMMA_SEP + BodyEntry.COLUMN_PWD + TEXT_TYPE + COMMA_SEP + BodyEntry.COLUMN_SHENFEN + TEXT_TYPE + COMMA_SEP + BodyEntry.COLUMN_SHIYUE + TEXT_TYPE + " )"; private static final String TIMESQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + TimeEntry.TABLE_NAME; private static final String STUSSQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + StudentsEntry.TABLE_NAME; private static final String BODYSQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + BodyEntry.TABLE_NAME; public static final int DATABASE_VERSION = 1; public static final String DATABASE_NAME = "FeedReader.db"; public SkbDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } public void onCreate(SQLiteDatabase db) { db.execSQL(TIMESQL_CREATE_ENTRIES); db.execSQL(STUSSQL_CREATE_ENTRIES); db.execSQL(BODYSQL_CREATE_ENTRIES); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // This database is only a cache for online data, so its upgrade policy is // to simply to discard the data and start over db.execSQL(TIMESQL_DELETE_ENTRIES); db.execSQL(STUSSQL_DELETE_ENTRIES); db.execSQL(BODYSQL_DELETE_ENTRIES); onCreate(db); } public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { onUpgrade(db, oldVersion, newVersion); } }
代碼中創建了三個表,個人認為如果用到多個表,這算是一種簡便的方法。
建好表以后創建數據表操作管理類,常用操作如下:
1、判斷表中是否有數據
public boolean isDataExist(){ int count = 0; SQLiteDatabase db = null; Cursor cursor = null; try { db = SkbApplication.getInstance().getDbHelper().getReadableDatabase(); // select count(Id) from Orders cursor = db.query(BodyEntry.TABLE_NAME, new String[]{"COUNT(" + BodyEntry._ID + ")"}, null, null, null, null, null); if (cursor.moveToFirst()) { count = cursor.getInt(0); } if (count > 0) return true; } catch (Exception e) { Log.e("db", "", e); } finally { if (cursor != null) { cursor.close(); } if (db != null) { db.close(); } } return false; }
注1:dbhelper寫到了application中,如下
public SkbDbHelper getDbHelper(){ if (dbHelper == null){ dbHelper = new SkbDbHelper(this); } return dbHelper; }
注2:bodyEntry為實體類,繼承自BaseColumns,提供了_ID等。
public static class StudentsEntry implements BaseColumns { public static final String TABLE_NAME = "students"; public static final String COLUMN_KID= "kid"; //課程id public static final String COLUMN_NAME = "name"; public static final String COLUMN_CLASS = "class"; public static final String COLUMN_CANJIA = "canjia"; // 0 不參加, 1參加 public static final String COLUMN_WENTI = "wenti"; // 備注 }
繼續表操作
2、查詢所有數據
public List<StudentsBean> getAllDate(){ String[] projection = { StudentsEntry._ID, StudentsEntry.COLUMN_KID, StudentsEntry.COLUMN_NAME, StudentsEntry.COLUMN_CLASS, StudentsEntry.COLUMN_CANJIA, StudentsEntry.COLUMN_WENTI }; SQLiteDatabase db = null; Cursor cursor = null; try { db = SkbApplication.getInstance().getDbHelper().getReadableDatabase(); // select * from Orders cursor = db.query(StudentsEntry.TABLE_NAME, projection, null, null, null, null, null); if (cursor.getCount() > 0) { List<StudentsBean> orderList = new ArrayList<StudentsBean>(cursor.getCount()); while (cursor.moveToNext()) { orderList.add(parseOrder(cursor)); } return orderList; } } catch (Exception e) { Log.e("db", "", e); } finally { if (cursor != null) { cursor.close(); } if (db != null) { db.close(); } } return null; }
3、插入數據
public boolean insertDate(String kid,String name,String sclass,String wenti){ SQLiteDatabase db = null; try { db = SkbApplication.getInstance().getDbHelper().getWritableDatabase(); db.beginTransaction(); ContentValues contentValues = new ContentValues(); contentValues.put(StudentsEntry.COLUMN_KID, kid); contentValues.put(StudentsEntry.COLUMN_NAME, name); contentValues.put(StudentsEntry.COLUMN_CLASS, sclass); contentValues.put(StudentsEntry.COLUMN_CANJIA, "0"); contentValues.put(StudentsEntry.COLUMN_WENTI, wenti); db.insert(StudentsEntry.TABLE_NAME, null, contentValues); Toast.makeText(context,"報名成功",Toast.LENGTH_SHORT).show(); db.setTransactionSuccessful(); return true; }catch (SQLiteConstraintException e){ Toast.makeText(context, "主鍵重復", Toast.LENGTH_SHORT).show(); }catch (Exception e){ Log.e("db", "", e); }finally { if (db != null) { db.endTransaction(); db.close(); } } return false; }
4、刪除數據
public boolean deleteOrder(String id) { // Define 'where' part of query. String selection = StudentsEntry.COLUMN_KID + " LIKE ?"; // Specify arguments in placeholder order. String[] selectionArgs = { id }; SQLiteDatabase db = null; try { db = SkbApplication.getInstance().getDbHelper().getWritableDatabase(); db.beginTransaction(); db.delete(StudentsEntry.TABLE_NAME, selection, selectionArgs); db.setTransactionSuccessful(); return true; } catch (Exception e) { Log.e("db", "", e); } finally { if (db != null) { db.endTransaction(); db.close(); } } return false; }
5、修改數據,此處查找_ID為“id”的數據,修改其COLUMN_CANJIA為“canjia”;
public boolean updateCanjia(String id,String canjia){ SQLiteDatabase db = null; try { db = SkbApplication.getInstance().getDbHelper().getWritableDatabase(); db.beginTransaction(); // update Orders set OrderPrice = 800 where Id = 6 ContentValues cv = new ContentValues(); cv.put(StudentsEntry.COLUMN_CANJIA, canjia); // Which row to update, based on the title String selection = StudentsEntry._ID + " = ?"; String[] selectionArgs = {id}; db.update(StudentsEntry.TABLE_NAME, cv, selection, selectionArgs); db.setTransactionSuccessful(); return true; } catch (Exception e) { Log.e("db", "", e); } finally { if (db != null) { db.endTransaction(); db.close(); } } return false; }
6、按條件查詢,查詢_ID為“id”並且COLUMN_CANJIA為“canjia”的數據。
public List<StudentsBean> gettitleBean(String id,String canjia){ String[] projection = { StudentsEntry._ID, StudentsEntry.COLUMN_KID, StudentsEntry.COLUMN_NAME, StudentsEntry.COLUMN_CLASS, StudentsEntry.COLUMN_CANJIA, StudentsEntry.COLUMN_WENTI }; // Filter results WHERE "title" = 'My Title' String selection = StudentsEntry.COLUMN_KID + " = ? and " + StudentsEntry.COLUMN_CANJIA + " = ?"; String[] selectionArgs = { id , canjia }; SQLiteDatabase db = null; Cursor cursor = null; try { db = SkbApplication.getInstance().getDbHelper().getReadableDatabase(); // select * from Orders where CustomName = 'Bor' cursor = db.query(StudentsEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, null); if (cursor.getCount() > 0) { List<StudentsBean> orderList = new ArrayList<StudentsBean>(cursor.getCount()); while (cursor.moveToNext()) { StudentsBean order = parseOrder(cursor); orderList.add(order); } return orderList; } } catch (Exception e) { Log.e("db", "", e); } finally { if (cursor != null) { cursor.close(); } if (db != null) { db.close(); } } return null; }
最后附上 數據庫數據插入list的語句
private StudentsBean parseOrder(Cursor cursor){ StudentsBean bean = new StudentsBean(); bean.setId(cursor.getInt(cursor.getColumnIndex(StudentsEntry._ID))); bean.setKid(cursor.getString(cursor.getColumnIndex(StudentsEntry.COLUMN_KID))); bean.setName(cursor.getString(cursor.getColumnIndex(StudentsEntry.COLUMN_NAME))); bean.setSclass(cursor.getString(cursor.getColumnIndex(StudentsEntry.COLUMN_CLASS))); bean.setCanjia(cursor.getString(cursor.getColumnIndex(StudentsEntry.COLUMN_CANJIA))); bean.setWenti(cursor.getString(cursor.getColumnIndex(StudentsEntry.COLUMN_WENTI))); return bean; }
目前用到這些。