android之SQLite的增删查改(个人觉得挺不错)

这篇博客详细介绍了SQLite数据库在Android中的使用,包括delete、insert、replace、update和query等基本操作。通过示例代码展示了如何进行数据的增删查改,以及创建和管理数据库的方法。

先介绍一下几个方法:

 

1:删除

public int delete (String table,String whereClause, String[] whereArgs)

Convenience method for deleting rows in the database.

Parameters
tablethe table to delete from
whereClausethe optional WHERE clause to apply when deleting. Passing null will delete all rows.
Returns
  • the number of rows affected if a whereClause is passed in, 0 otherwise. To remove all rows and get a count pass "1" as the whereClause.

2, 插入

public long insert (String table,String nullColumnHack, ContentValues values)

Convenience method for inserting a row into the database.

Parameters
tablethe table to insert the row into
nullColumnHackSQL doesn't allow inserting a completely empty row, so if initialValues is empty this column will explicitly be assigned a NULL value
valuesthis map contains the initial column values for the row. The keys should be the column names and the values the column values
Returns
  • the row ID of the newly inserted row, or -1 if an error occurred
3 修改
public long replace (String table,String nullColumnHack, ContentValues initialValues)

Convenience method for replacing a row in the database.

Parameters
tablethe table in which to replace the row
nullColumnHackSQL doesn't allow inserting a completely empty row, so if initialValues is empty this row will explicitly be assigned a NULL value
initialValuesthis map contains the initial column values for the row. The key
Returns
  • the row ID of the newly inserted row, or -1 if an error occurred

4 更新
public int update (String table,ContentValues values, String whereClause, String[] whereArgs)

Convenience method for updating rows in the database.

Parameters
tablethe table to update in
valuesa map from column names to new column values. null is a valid value that will be translated to NULL.
whereClausethe optional WHERE clause to apply when updating. Passing null will update all rows.
Returns
  • the number of rows affected

5 查询
public Cursor query (String table,String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)

Query the given table, returning a Cursor over the result set.

Parameters
tableThe table name to compile the query against.
columnsA list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.
selectionA filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table.
selectionArgsYou may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.
groupByA filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped.
havingA filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used.
orderByHow to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.
limitLimits the number of rows returned by the query, formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Returns
  • A Cursor object, which is positioned before the first entry
See Also



privatestaticfinal StringDATABASE_CREATE =

           "create table notes (_id integer primary key autoincrement, "

                   + "title text not null, body text not null);";

 

   privatestaticfinal StringDATABASE_NAME ="data";

   privatestaticfinal StringDATABASE_TABLE ="notes";

   privatestaticfinalintDATABASE_VERSION = 2;

 

   privatefinal ContextmCtx;

 

   privatestaticclass DatabaseHelperextends SQLiteOpenHelper {

 

       DatabaseHelper(Context context) {

           super(context,DATABASE_NAME,null,DATABASE_VERSION);

       }  //创建一个名字为DATABASE_NAME=data 的数据库

 

       @Override

       publicvoid onCreate(SQLiteDatabase db) {

 

           db.execSQL(DATABASE_CREATE);//执行 DATABASE_CREATE语句 创建表notes

       }

 

       @Override

       publicvoid onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion) {

           Log.w(TAG,"Upgrading database from version " + oldVersion +" to "

                   + newVersion + ", which will destroy all old data");

           db.execSQL("DROP TABLE IF EXISTS notes");//执行SQL语句

           onCreate(db);  //如果数据库改变,drop旧表,重新创建新表

       }

   }

   public NotesDbAdapter(Context ctx) {

       this.mCtx = ctx;

   }

 

   public NotesDbAdapter open()throws SQLException {

       mDbHelper =new DatabaseHelper(mCtx);

       mDb =mDbHelper.getWritableDatabase();

       returnthis;

   }

   

   publicvoid close() {

       mDbHelper.close();

   }

   publiclong createNote(String title, String body) {

       ContentValues initialValues = new ContentValues();

       initialValues.put(KEY_TITLE, title);

       initialValues.put(KEY_BODY, body);

       returnmDb.insert(DATABASE_TABLE,null, initialValues);//插入表项

   }

 

   publicboolean deleteNote(long rowId) {

        //删除KEY_ROWID=rowId的行

       returnmDb.delete(DATABASE_TABLE,KEY_ROWID +"=" + rowId,null) > 0;

   }  

 

    */

   public Cursor fetchAllNotes() {

      //返回所有的记事

       returnmDb.query(DATABASE_TABLE,new String[] {KEY_ROWID,KEY_TITLE,

               KEY_BODY},null,null,null,null,null);

   }

 

   public Cursor fetchNote(long rowId) throws SQLException {

 

       Cursor mCursor =

 

               mDb.query(true,DATABASE_TABLE,new String[] {KEY_ROWID,

                       KEY_TITLE,KEY_BODY},KEY_ROWID +"=" + rowId,null,

                       null,null,null,null);

       if (mCursor !=null) {

           mCursor.moveToFirst();

       }

       return mCursor;

 

   }

   publicboolean updateNote(long rowId, String title, String body) {

       ContentValues args = new ContentValues();

       args.put(KEY_TITLE, title);

       args.put(KEY_BODY, body);

        //更新表

       returnmDb.update(DATABASE_TABLE, args, KEY_ROWID +"=" + rowId,null) > 0;

   }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值