生活随笔
收集整理的這篇文章主要介紹了
封装数据库一系列操作,包括打开/新建数据库,增删改查
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
該類如何使用:定義變量
/*
NoteDbHelper noteDbHelper;
noteDbHelper=new NoteDbHelper(MainActivity.this);
//必須傳一個MainActivity.this參數
noteDbHelper.open();
noteDbHelper.createNote();
*/
public class NoteDbHelper {private String LOGTAG
="NoteDbHelper";private static final String DB_NAME
= "data1";private static final int DB_VERSION
= 1;private static final String TABLE_NAME
= "notes";static final String KEY_TITLE
= "title";static final String KEY_BODY
= "body";static final String KEY_ROWID
= "_id";private Context ctx
= null
;private NoteSQLiteHelper dbHelper
= null
;private SQLiteDatabase db
= null
;
/*
構造函數*/
public NoteDbHelper(Context ctx
) {this.ctx
= ctx
;}public NoteDbHelper
open(){dbHelper
= new NoteSQLiteHelper(ctx
, DB_NAME
, null
, DB_VERSION
) ;db
=dbHelper
.getWritableDatabase();return this;}public int createNote(String title
, String body
) {ContentValues values
= new ContentValues();values
.put(KEY_TITLE
, title
);values
.put(KEY_BODY
, body
);int rowId
= (int)db
.insert(TABLE_NAME
, null
, values
);return rowId
;}public boolean updateNote(long rowId
, String title
, String body
) {ContentValues values
= new ContentValues();values
.put(KEY_TITLE
, title
);values
.put(KEY_BODY
, body
);int updatedRows
= db
.update(TABLE_NAME
, values
, KEY_ROWID
+ "=" + rowId
, null
);return updatedRows
> 0;}public boolean deleteNote(long rowId
) {int deletedRows
= db
.delete(TABLE_NAME
, KEY_ROWID
+ "=" + rowId
, null
);return deletedRows
> 0;}public Cursor
retrieveAllNotes() {Cursor cur
= db
.query(TABLE_NAME
, null
,null
, null
, null
, null
, null
);return cur
;}public List
<Notebean> getAllNotes(){Cursor c
=retrieveAllNotes();ArrayList
<Notebean> itemList
= new ArrayList<Notebean>();while (c
.moveToNext()) {Notebean item
= new Notebean();int index
=c
.getColumnIndex(KEY_ROWID
);int myid
= c
.getInt(index
);item
.setId(myid
);item
.setTitle(c
.getString(c
.getColumnIndex(KEY_TITLE
)));item
.setBody(c
.getString(c
.getColumnIndex(KEY_BODY
)));Log
.e(LOGTAG
, "Notebean-" + item
.toString());itemList
.add(item
);}return itemList
;}}
可能會有點亂,仔細看看就知道大概原理。
與50位技術專家面對面20年技術見證,附贈技術全景圖
總結
以上是生活随笔為你收集整理的封装数据库一系列操作,包括打开/新建数据库,增删改查的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。