Android数据库SQLite demo

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Song_74110/article/details/81008415

简介

Android自带了一种轻量级数据库SQLite,而且它支持SQL语句。

SQLiteOpenHelper

是SQLiteDatabase一个辅助类,主要生成一个数据库,并对数据库进行管理。SQLiteOpenHelper 是一个抽象类,我们通常需要继承它,并且实现里面的3个函数:

  • onCreate(SQLiteDatabase db)
    在数据库第一次生成的时候会调用这个方法,也就是说,只有在创建数据库的时候才会调用,当然也有一些其它的情况,一般我们在这个方法里边生成数据库表。

  • onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    当数据库需要升级的时候,Android系统会主动的调用这个方法。一般我们在这个方法里边删除数据表,并建立新的数据表。

  • insert(String table, String nullColumnHack, ContentValues values)
    api里面是这样描述的,插入一行数据到数据库里面。

    /**
     * Convenience method for inserting a row into the database.
     *
     * @param table the table to insert the row into
     * @param nullColumnHack optional; may be <code>null</code>.
     *            SQL doesn't allow inserting a completely empty row without
     *            naming at least one column name.  If your provided <code>values</code> is
     *            empty, no column names are known and an empty row can't be inserted.
     *            If not set to null, the <code>nullColumnHack</code> parameter
     *            provides the name of nullable column name to explicitly insert a NULL into
     *            in the case where your <code>values</code> is empty.
     * @param values this map contains the initial column values for the
     *            row. The keys should be the column names and the values the
     *            column values
     * @return the row ID of the newly inserted row, or -1 if an error occurred
     */
    public long insert(String table, String nullColumnHack, ContentValues values) {
        try {
            return insertWithOnConflict(table, nullColumnHack, values, CONFLICT_NONE);
        } catch (SQLException e) {
            Log.e(TAG, "Error inserting " + values, e);
            return -1;
        }
    }
  • delete(String table, String whereClause, String[] whereArgs)
    api里面的描述,参数(表名,删除条件,删除条件值数组)
    /**
     * Convenience method for deleting rows in the database.
     *
     * @param table the table to delete from
     * @param whereClause the optional WHERE clause to apply when deleting.
     *            Passing null will delete all rows.
     * @param whereArgs You may include ?s in the where clause, which
     *            will be replaced by the values from whereArgs. The values
     *            will be bound as Strings.
     * @return 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.
     */
    public int delete(String table, String whereClause, String[] whereArgs) {
        acquireReference();
        try {
            SQLiteStatement statement =  new SQLiteStatement(this, "DELETE FROM " + table +
                    (!TextUtils.isEmpty(whereClause) ? " WHERE " + whereClause : ""), whereArgs);
            try {
                return statement.executeUpdateDelete();
            } finally {
                statement.close();
            }
        } finally {
            releaseReference();
        }
    }
  • update(String table, ContentValues values, String whereClause, String[] whereArgs)
    api里面描述,参数(表名,更新值,更新条件,更新条件值数组)
    /**
     * Convenience method for updating rows in the database.
     *
     * @param table the table to update in
     * @param values a map from column names to new column values. null is a
     *            valid value that will be translated to NULL.
     * @param whereClause the optional WHERE clause to apply when updating.
     *            Passing null will update all rows.
     * @param whereArgs You may include ?s in the where clause, which
     *            will be replaced by the values from whereArgs. The values
     *            will be bound as Strings.
     * @return the number of rows affected
     */
    public int update(String table, ContentValues values, String whereClause, String[] whereArgs) {
        return updateWithOnConflict(table, values, whereClause, whereArgs, CONFLICT_NONE);
    }
  • query(String table, String[] columns, String selection,
    String[] selectionArgs, String groupBy, String having,
    String orderBy)
    查询返回的是一个Cursor,参数(表名称,列名数组,查询条件,查询条件值数组,分组列,分组条件,排序,分页查询限制)
    /**
     * Query the given table, returning a {@link Cursor} over the result set.
     *
     * @param table The table name to compile the query against.
     * @param columns A 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.
     * @param selection A 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.
     * @param selectionArgs You 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.
     * @param groupBy A 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.
     * @param having A 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.
     * @param orderBy How 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.
     * @return A {@link Cursor} object, which is positioned before the first entry. Note that
     * {@link Cursor}s are not synchronized, see the documentation for more details.
     * @see Cursor
     */
    public Cursor query(String table, String[] columns, String selection,
            String[] selectionArgs, String groupBy, String having,
            String orderBy) {

        return query(false, table, columns, selection, selectionArgs, groupBy,
                having, orderBy, null /* limit */);
    }

demo继承SQLiteOpenHelper代码

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DemoHelper extends SQLiteOpenHelper {

    public static final int VERSION = 1;
    public static final String DB_TABLE = "demo_table";

    public DemoHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version){
        super(context,name,factory,version);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "create table "+DB_TABLE+"(id int,tellname varchar(20),tell varchar(20))";
        Log.d("song--->","create table demo_table");
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.d("song--->","update table demo_table");
    }
}

使用DemoHelper代码

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    DemoHelper mDemoHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    private void createDabase(){
        //mDemoHelper = new DemoHelper(this, "demo_db", null, DemoHelper.VERSION);
        Log.d("song--->","create db");
        mDemoHelper = new DemoHelper(this, "demo_db", null, DemoHelper.VERSION);
    }

    public void clickCreate(View v){
        createDabase();
    }

    public void clickInsert(View v){
        //id int,name varchar(20),tell varchar(20)
        if(null == mDemoHelper) createDabase();
        SQLiteDatabase db = mDemoHelper.getWritableDatabase();

        //方法一
//        ContentValues values = new ContentValues();
//        values.put("id","1");
//        values.put("tellname","song");
//        values.put("tell","110");
//        db.insert(DemoHelper.DB_TABLE,null,values);
//        Log.d("song--->","insert values id = 1,tellname = song,tell = 110");

        //方法二:
        String sqlInsert = "insert into "+DemoHelper.DB_TABLE+"(id,tellname,tell) values('3','InsertSong','111')";
        db.execSQL(sqlInsert);
        Log.d("song--->","insert values id = 3,song = InsertSong,tell = 111");

        db.close();
    }

    public void clickDelete(View v){
        if(null == mDemoHelper) createDabase();
        SQLiteDatabase db = mDemoHelper.getWritableDatabase();

        //方法一:
//        db.delete(DemoHelper.DB_TABLE,"id=?",new String[]{"1"});
//        Log.d("song--->","delete values id = 1");

        //方法二:
        String sqlDelete = "delete from "+DemoHelper.DB_TABLE+" where id = 3";
        db.execSQL(sqlDelete);
        Log.d("song--->","delete values id = 3");

        db.close();
    }

    public void clickquery(View v){
        if(null == mDemoHelper) createDabase();
        SQLiteDatabase db = mDemoHelper.getReadableDatabase();
        Cursor cursor = db.query(DemoHelper.DB_TABLE, /*new String[]{"id","tellname","tell"}*/null, /*"id=?"*/null, /*new String[]{"1"}*/null, null, null, null);
        //Cursor cursor = db.query(DemoHelper.DB_TABLE, new String[]{"id","tellname","tell"}, "id=?", new String[]{"1"}, null, null, null);
        while (cursor.moveToNext()){
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            String tellname = cursor.getString(cursor.getColumnIndex("tellname"));
            String tell = cursor.getString(cursor.getColumnIndex("tell"));
            Log.d("song--->","query message id = "+id+",tellname = "+tellname+",tell = "+tell);
        }
        cursor.close();
        db.close();

    }

    public void clickUpdate(View v){
        if(null == mDemoHelper) createDabase();
        SQLiteDatabase db = mDemoHelper.getWritableDatabase();

        //方法一:
//        ContentValues contentValues = new ContentValues();
//        contentValues.put("tellname","song111");
//        db.update(DemoHelper.DB_TABLE, contentValues, "id=?", new String[]{"1"});

        //方法二:
        String sqlUpdate = "update "+DemoHelper.DB_TABLE+" set tellname = 'songUpdate' where id = 3";
        db.execSQL(sqlUpdate);

        Log.d("song--->","update...");
        clickquery(v);
        db.close();
    }

}

布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_marginTop="4dp"
        android:background="@color/colorGreay"
        android:gravity="center"
        android:onClick="clickCreate"

        android:text="onClickCreate" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_marginTop="4dp"
        android:background="@color/colorGreay"
        android:gravity="center"
        android:onClick="clickInsert"
        android:text="onClickInsert" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_marginTop="4dp"
        android:background="@color/colorGreay"
        android:gravity="center"
        android:onClick="clickDelete"
        android:text="onClickDelete" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_marginTop="4dp"
        android:background="@color/colorGreay"
        android:gravity="center"
        android:onClick="clickquery"
        android:text="onClickQuery" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_marginTop="4dp"
        android:background="@color/colorGreay"
        android:gravity="center"
        android:onClick="clickUpdate"
        android:text="onClickUpdate" />

</LinearLayout>

demo地址

最后附上demo的地址,感兴趣的同学可以去下载玩玩,点击传送

猜你喜欢

转载自blog.csdn.net/Song_74110/article/details/81008415