Android对数据库的基本操作

用Android创建一个数据库

在我们写一个应用的时候, 如果要在实际中能够使用, 就不能将数据设置成某些固定的值, 而是能在数据库中读取数据, 以及对数据进行各种操作. 这样, 我们就要在Android程序中通过代码来对数据库以及数据库中的数据进行操作.

首先 将数据库中的表的样式(需要那些字段)以常量的形式定义出来, 并且要将一些约束条件添加上

    public static final String CREATE_TABLE_COST =
            "create table cost (_id integer primary key autoincrement, money double not null default 0, use_time long, type INTEGER)) ";
    public static final String CREATE_TABLE_INCOM =
            "create table cost (_id integer primary key autoincrement, money double not null default 0, type integer default 0) ";

构造方法 对数据库的上下文和文件名等参数进行初始化

    public DbHelper(Context context){
        //Context:在内部存储区创建数据库文件
        //参2: 数据库文件名
        //参4:版本号  当前程序在代码中设置的版本号信息, 这个版本号应该是程序最新的数据库版本. 自动检测手机中的数据库版本, 如果不一致, 就进行数据库的升级
        super(context, "myapp", null, 1);
    }

有了数据库之后, 自然是要创建我们所需要的一些表, 来存储我们需要的数据, 有些时候, 需要把数据库中的数据展示到ListView中, 那么我们在定义表的时候就必须要有一个_id的字段(必须有).

    @Override
    public void onCreate(SQLiteDatabase db) {
        //如果数据库表 需要显示在ListView中, 表中必须包含_id字段
        db.execSQL(CREATE_TABLE_COST);
        Log.d("DbHelper", "OnCreate");
    }

考虑到用户需求, 我们的数据会经常发生改变, 这样, 我们的版本就会不断的升级, 主要是更新数据库. 例如: 增加一张表, 为某一张表添加一个字段等等, 所以, 就需要检测版本号, 判断是否要更新.
代码如下:

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //TODO:考虑版本升级的实现
        if (newVersion == 2){
            db.execSQL(CREATE_TABLE_INCOM);
        }
    }

有了数据库, 有了数据表, 接下来就要进行对数据的增删改查, 数据一旦发生改变, ListView中显示的数据也要有所改变, 此时, 就需要查询所有数据. 即每一次就行数据的修改后, 都要进行一次查询. 查询的代码如下:

//将要查询的表的名字传进去
   private Cursor requeryCursor() {
        Cursor cursor =
                database.query(
                        "cost", null,
                        "type = ?", new String[]{"1"},
                        null, null, "money desc");
        //更新游标
        adapter.changeCursor(cursor);
        //刷新页面
        adapter.notifyDataSetChanged();
        return cursor;
    }

增删改查操作的实现

添加

这里, 我们以添加按钮为例, 即 按下”添加”按钮就自动添加一条数据, 该数据是死的, 不能灵活添加.

 @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.add:
            //ContentValues
                ContentValues values = new ContentValues();
                values.put("money", 30.0);
                values.put("use_time", System.currentTimeMillis());
                values.put("type", 1);
                //参数2: 如果valuse等于null, 或者内部为空, 那么参2就是一个列名, 这个列可以为空
                long rowId = database.insert("cost", null, values);
                requeryCursor();
                Toast.makeText(MainActivity.this, "添加记录", Toast.LENGTH_SHORT).show();
                //刷新页面
                adapter.notifyDataSetChanged();
        }
    }

删除操作

实现长按ListView中某一条数据就删除的效果. 删除的时候要确定删除的数据在哪个表中, 是哪一条数据(删除的条件, 比如: 将id是?的删掉, 年龄是?的删掉, 将性别是?的删掉)

   @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        boolean ret = false;
        //删除操作
        //返回删除的记录数            要删除数据所在的表   删除的条件   ?所表示内容
        int deleteNumber = database.delete("cost", "_id = ?", new String[]{Long.toString(id)});
        //删除完成后进行查询
        requeryCursor();
        Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
        return ret;
    }

修改数据

比如说, 我们要做一个记事本一类的软件, 那么, 对我们保存的数据进行修改是必不可少的. 如果要进行修改数据, 有一个编辑状态是必不可少的.
现在假定点击一下进入编辑模式, 首先就要给每一个ListView条目添加点击事件, 并且在Intent中赋上要修改的条目的id的值

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(this, EditActivity.class);
        intent.putExtra("recordId", id);
        startActivity(intent);
    }

要进行修改, 首先要打开数据库, 并且可以做修改等操作, 在这个过程中, 我们要多次进行判空, 如果不判空的话可能会造成空指针异常. 另外, 在查找值的时候会用到Cursor , 但是当我们用完之后一定要将其关闭, 否则会造成内存泄漏等情况.

        DbHelper dbHelper = new DbHelper(this);
        database = dbHelper.getWritableDatabase();
        recordId = -1;
        Intent intent = getIntent();
        recordId = intent.getLongExtra("recordId", -1);
        //判断是否得到id
        if (recordId != -1){
        //得到一个游标
            Cursor cursor = database.query("cost", null,
                    "_id = ?",
                    new String[]{Long.toString(recordId)},
                    null, null, null);
            if (cursor != null){
                if (cursor.moveToNext()){
                    int index = cursor.getColumnIndex("money");
                    if (index != -1){
                        double money = cursor.getDouble(index);
                        mMoney.setText(Double.toString(money));
                    }
                    index = cursor.getColumnIndex("type");
                    if (index != -1){
                        int type = cursor.getInt(index);
                        mType.setText(Integer.toString(type));
                    }
                }
                cursor.close();
            }
        }

设置保存的单击事件, 实现保存

    public void onSave(View view) {
        //更新数据
        double money = 0;
        int type = 0;
//这里对str进行了重复使用
        String str = mMoney.getText().toString();
        money = Double.parseDouble(str);

        str = mType.getText().toString();
        type = Integer.parseInt(str);

        if (recordId != -1){
            ContentValues values = new ContentValues();
            //赋值
            values.put("money", money);
            values.put("type", type);
            //得到修改的数据的条数
            int num = database.update("cost",
                    values, "_id = ?",
                    new String[]{Long.toString(recordId)});
            if (num > 0) {
                //TODO: 更新成功
                finish();
            }else {
                Toast.makeText(EditActivity.this, "更新失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

一定行就是用Android代码对数据库进行一些基本操作(创建数据库, 对表的增删改查).

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值