SQLite之增删改查(二)DAO方法

新建Dao类来操作数据库的增删改查

package com.example.mysqlite;

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

// 操作数据增删改查
public class Dao {
    private final DatabaseHelper mhelper;// 定义DatabaseHelper类
    private final static String TAG = "DAO";

    public Dao(Context context){// 构造方法
        mhelper = new DatabaseHelper(context);
    }
(一)增加某一行数据用“insert into”
    public void insert(){
        SQLiteDatabase db = mhelper.getReadableDatabase();
        // values后使用占位符,防止sql注入
        String sql = "insert into "+Constant.TABLE_NAME+"(_id,name,age,score,phone,address) values(?,?,?,?,?,?)";
        db.execSQL(sql,new Object[]{1,"LIU",20,90,123456,"CN"});// 增加的数据放入Object对象
        db.close();// 关闭数据库
    }
(二)删除某一行数据用“delete from”,用where来设置删除条件
    public void delete(){
        SQLiteDatabase db = mhelper.getReadableDatabase();
        String sql = "delete from "+Constant.TABLE_NAME+" where name = l12 ";
        db.execSQL(sql);
        db.close();
    }
(三)更改某行数据用“update”,set重设某个属性值,where设置更改条件
    public void update(){
        SQLiteDatabase db = mhelper.getReadableDatabase();
        String sql = "update "+Constant.TABLE_NAME+" set age = 24 where name = LIU ";
        db.execSQL(sql);
        db.close();
    }
(四)查询某条数据用“select",但execSQL没有返回值,换用rawQuery方法,返回查询得到的游标。
    public void query(){
        SQLiteDatabase db = mhelper.getReadableDatabase();
//        String sql = "select * from "+Constant.TABLE_NAME+" where name = lcz ";//可通过where设置查询条件
        String sql = "select * from "+Constant.TABLE_NAME;
        Cursor cursor = db.rawQuery(sql,null);
        while (cursor.moveToNext()){ // moveToNext说明还有数据,假设有下一行
            int index = cursor.getColumnIndex("name");// 获取属性值为“name”的列的索引值
            String name = cursor.getColumnName(index);// 获取索引值为index的列的字符串内容
            Log.d(TAG, "name ="+name);
        }
        cursor.close();// Cursor是种资源,不用需关闭
        db.close();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值