【Android】SQLite 创建数据库,并实现增删改查

SQLite

SQLite 是Android内置的数据库,它是一款轻量级数据库,运算快,占用资源少。
下面让我们来学习一下这个数据库的基本使用:

创建和升级数据库

Android提供了一个SQLiteOpenHelper的抽象类来让我们对数据库进行创建与更新
这个抽象方法中有两个抽象方法需要我们重写,分别是onCreate,onUpgrade,首
先我们创建一个继承SQLiteOpenHelper的类,并重写上述的两个方法和构造器;


/**
 * Created by wj on 2017/8/11.
 */

public class MyDbHelper extends SQLiteOpenHelper {
    private Context mContext;
    public MyDbHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        mContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table Stu(" +
                "id integer primary key autoincrement," +
                "stuName text)");
        Toast.makeText(mContext,"DB is create.",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

在onCreate方法中我用.execSQL方法创建了一个表,很明显方法里是一个SQL语句。
这样我们在创建数据库的同时就把表创建好了。
接下来我们在活动中去调用它

Button create = (Button)findViewById(R.id.button_create);
 //创建

        // 获取SQLiteOpenHelper实例
        // 第一个参数是Context无需多言
        // 第二个参数是要创建的数据库名
        // 第三个参数是查询数据返回的自定义Cursor这里我们传入Null就行
        // 第四个参数则是版本号
        final MyDbHelper myDbHelper = new MyDbHelper(MainActivity.this,"Stu.db",null,1);
        create.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //执行该方法后会自动检测是否存在该数据库,若无则执行onCreate方法
                // 同时判断版本号,若版本更新了,则会执行onUpgrade方法
                myDbHelper.getWritableDatabase();
            }
        });

再看看onUpgrade方法,这里我没有写,如果要升级数据库的话,我们只要在onUpgrade
方法中用.execSQL执行相应SQl语句

插入数据

对数据库进行操作,首先我们需要通过getWritableDatabase获取一个SQLiteDatabase
实例,然后通过该实例的.insert()方法进行插入操作

   final Button insert = (Button)findViewById(R.id.button_insert);
   final EditText insertText = (EditText)findViewById(R.id.edit_insert);
 //插入
        insert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (insertText.getText().toString().equals("")){
                    Toast.makeText(MainActivity.this,"插入失败",Toast.LENGTH_SHORT).show();
                }else{
                    //获取SQLiteDatabase实例
                    SQLiteDatabase db = myDbHelper.getWritableDatabase();
                    ContentValues values = new ContentValues();
                    values.put("stuName",insertText.getText().toString());
                    //插入
                    //第一个参数表名
                    //第二个参数用于制定一个字段让某些可为空的列自动赋null
                    //第三个参数是一个ContentValues对象
                    db.insert("Stu",null,values);
                    values.clear();
                    Toast.makeText(MainActivity.this,"插入成功",Toast.LENGTH_SHORT).show();
                }
            }
        });

删除数据

同样是先get一个SQLiteDatabase实例,然后通过其.delete()方法进行删除操作

Button delete = (Button)findViewById(R.id.button_delete);
final EditText deleteText = (EditText)findViewById(R.id.edit_delete);
 //删除
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SQLiteDatabase db = myDbHelper.getWritableDatabase();
                //delete返回值为数据库受影响行数(int类型),通过返回值判断删除结果
                //第一个参数是表名
                //第二个参数与第三个参数是约束条件
                if (db.delete("Stu","id = ?",new String[]{deleteText.getText().toString()})==0){
                    Toast.makeText(MainActivity.this,"删除失败",Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(MainActivity.this,"删除成功",Toast.LENGTH_SHORT).show();
                }

            }
        });

更新数据

通过SQLiteDatabase实例的.update()方法进行更新操作

 Button update = (Button)findViewById(R.id.button_update);
 final EditText updateText = (EditText)findViewById(R.id.edit_update_text);
 final EditText updateId = (EditText)findViewById(R.id.edit_update_id);
//更新
        update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SQLiteDatabase db = myDbHelper.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put("stuName",updateText.getText().toString());
                //通过Update方法的返回值判断更新结果
                //第一个参数为表名
                //第二个参数为ConetentValues对象
                //第三个与第四个参数为约束条件
                if (db.update("Stu",values,"id = ?",new String[]{updateId.getText().toString()})==0){
                    Toast.makeText(MainActivity.this,"更新失败",Toast.LENGTH_SHORT).show();
                }
                else{
                    Toast.makeText(MainActivity.this,"更新成功",Toast.LENGTH_SHORT).show();
                }
            }
        });

查询数据

终于到了最重要的查询了,没错,这次还是要get一个SQLiteDatabase实例,
用其.query()方法进行操作,但是这个方法却足足有至少7个参数
让我们看看官方文档描述

Parameters

table The table name to compile the query against.

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.

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.

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.

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.

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.

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.

limit Limits the number of rows returned by the query, formatted as
LIMIT clause. Passing null denotes no LIMIT clause.

通过查看官方文挡我们可以大概了解各个参数的作用,在这个Demo中我仅仅是
为了查询所有数据,所以只在第一个参数上写上表名,其他参数都为null来表示
查询该表的所有数据,并且这些数据都会被返回到一个Cursor对象中,我们可以
通过这个Cursor对象获取数据

 Button query = (Button)findViewById(R.id.button_query);
 //查询
        query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                queryText.setText("");
                SQLiteDatabase db = myDbHelper.getWritableDatabase();
                //查询,并把结果存到一个Cursor对象
                Cursor cursor = db.query("Stu",null,null,null,null,null,null);
                if (cursor.moveToFirst()){
                    do {
                        queryText.append("id: "+cursor.getString(cursor.getColumnIndex("id"))+"\n");
                        queryText.append("name:"+cursor.getString(cursor.getColumnIndex("stuName"))+"\n");
                    }while(cursor.moveToNext());
                }
                cursor.close();
            }
        });

到这里,我们已经完成了SQLite数据的创建,并进行了增删改查操作
这个Demo在GitHub:
点击这里进入GitHub

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值