When using SQLite, we usually encapsulate a SQLiteOpenHelper class directly and then operate the class. So here I will mainly talk about how to use SQLiteOpenHelper.
Package com. android. liu. sqlite;
Import android. content. ContentValues;
Import android. content. Context;
Import android. database. Cursor;
Import android. database. SQLException;
Import android. database. sqlite. SQLiteDatabase;
Import android. database. sqlite. SQLiteOpenHelper;
Public class MyDataBaseHelper {
Public static final String TAG = "MyDataBaseHelper ";
Public static final String KEY_ID = "_ id ";
Public static final String KEY_USERNAME = "username ";
Public static final String KEY_SEX = "sex ";
Public static final String DB_NAME = "user. db ";
Public static final String DB_TABLE = "userTbl ";
Public static final int DB_VERSION = 1;
Public static final String DB_CREATE = "create table" + DB_TABLE + "(" + KEY_ID + "integer primary key," + KEY_USERNAME + "TEXT" + KEY_SEX + "TEXT )";
Private Context mContext = null;
Private SQLiteDatabase mSQLiteDatabase = null;
Private DatabaseHelper mDatabaseHelper = null;
Private static class DatabaseHelper extends SQLiteOpenHelper {
Public DatabaseHelper (Context context ){
Super (context, DB_NAME, null, DB_VERSION );
}
@ Override
Public void onCreate (SQLiteDatabase db ){
Db.exe cSQL (DB_CREATE );
}
@ Override
Public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion ){
Db.exe cSQL ("DROP DB_TABLE if exists notes ");
OnCreate (db );
}};
Public MyDataBaseHelper (Context context)
{
MContext = context;
}
Public void open () throws SQLException
{
MDatabaseHelper = new DatabaseHelper (mContext );
MSQLiteDatabase = mDatabaseHelper. getWritableDatabase ();
}
Public void close ()
{
MDatabaseHelper. close ();
}
/** Insert a data entry */
Public long insertData (int num, String data, String sex)
{
ContentValues initialValues = new ContentValues ();
InitialValues. put (KEY_ID, num );
InitialValues. put (KEY_USERNAME, data );
InitialValues. put (KEY_SEX, sex );
Return mSQLiteDatabase. insert (DB_TABLE, KEY_ID, initialValues );
}
/** Delete a piece of data */
Public boolean deleteData (long rowId)
{
Return mSQLiteDatabase. delete (DB_TABLE, KEY_ID + "=" + rowId, null)> 0;
}
/**
* Query all data
**/
Public Cursor fetchAllData ()
{
Return mSQLiteDatabase. query (DB_TABLE, new String [] {KEY_ID, KEY_USERNAME, KEY_SEX}, null );
}
/** Query specified data */
Public Cursor fetchData (long rowId) throws SQLException
{
Cursor mCursor = mSQLiteDatabase. query (true, DB_TABLE, new String [] {KEY_ID, KEY_USERNAME, KEY_SEX}, KEY_ID + "=" + rowId, null, null );
If (mCursor! = Null)
{
MCursor. moveToFirst ();
}
Return mCursor;
}
/**
* Update a data record */
Public boolean updateData (long rowId, String username, String sex)
{
ContentValues args = new ContentValues ();
Args. put (KEY_USERNAME, username );
Args. put (KEY_SEX, sex );
Return mSQLiteDatabase. update (DB_TABLE, args, KEY_ID + "=" + rowId, null)> 0;
}
}