android sqlite demo 源码

源码这里很多逻辑都写在一起了,要使用其他逻辑需要屏蔽一些代码,代码比较简单,不做过多解释,有问题评论。

Activity代码

package com.uyac.andriodsqlite;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private String TAG = "MainActivity";
    private Context context;
    private RecyclerView recyclerview;
    private List<PersonModel> mList;
    private RecyclerAdapter mAdapter;
    private Button add, delete, modify, query,update;
    private MySqliteHelper mySqliteHelper;

    private Random mRandom;
    //名字数组,用于添加数据时随机
    private String nameArray[] = {"大一", "小二", "张三", "李四", "王五", "马六", "胡七", "王八", "金九", "银十", "天地", "玄黄", "宇宙", "洪荒", "嘻嘻", "欣欣向荣", "小明", "小红帽", "五天", "陈奕迅"};
    private String addressArray[] = {"北京市东花市北里20号楼6单元501室",
            "虹口区西康南路125弄34号201室 ",
            "湖北省荆州市红苑大酒店 李有财 ",
            "河南南阳市八一路272号特钢公司",
            "广东中山市东区亨达花园7栋702",
            "福建省厦门市莲花五村龙昌里34号601室",
            "山东省青岛市开平路53号国棉四厂二宿舍1号楼2单元204户甲",
            "河南省南阳市中州路42号",
            "中国四川省江油市川西北矿区采气一队 ",
            "北京市朝阳区霄云路50号",
            "北京市西城区槐柏树街22号",
            "广东省广州市越秀区中山六路",
            "上海市浦东新区x606"};
    private int ageArray[] = {464, 654, 564, 56, 456, 456, 4, 56131, 8, 1, 3, 556, 464, 611, 66, 5, 79, 9, 8, 79, 1, 100, 12, 15, 10000};
    private int isBoyArray[] = {1, 1, 0, 1, 0, 10, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 01, 0, 1, 0, 0, 0, 0,};
    private int imgArray[] = {R.mipmap.ic_launcher, R.mipmap.pic_1, R.mipmap.pic_2, R.mipmap.pic_3, R.mipmap.pic_4, R.mipmap.pic_5, R.mipmap.pic_6, R.mipmap.pic_7, R.mipmap.pic_8, R.mipmap.pic_9, R.mipmap.pic_10, R.mipmap.pic_11, R.mipmap.pic_12, R.mipmap.pic_spc};
    private byte picArray[][];

    //用于更新的版本号
    private int currentVersion;



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

        context = this;

        viewInit();
        dataInit();
        eventInit();


    }


    private void viewInit() {
        // TODO Auto-generated method stub

        recyclerview = (RecyclerView) findViewById(R.id.recyclerview);
        add = (Button) findViewById(R.id.add);
        delete = (Button) findViewById(R.id.delete);
        modify = (Button) findViewById(R.id.modify);
        query = (Button) findViewById(R.id.query);
        update = (Button) findViewById(R.id.update);
    }

    private void dataInit() {
        // TODO Auto-generated method stub

        mRandom = new Random();
        mySqliteHelper = new MySqliteHelper(context, Constants.DB_NAME, null, Constants.DB_VERSION);
        currentVersion = Constants.DB_VERSION;
        mList = new ArrayList<>();
        mAdapter = new RecyclerAdapter(context, mList);
        recyclerview.setAdapter(mAdapter);
        recyclerview.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));

        //加载图片
        loadImg();

    }

    private void eventInit() {
        // TODO Auto-generated method stub
        add.setOnClickListener(this);
        delete.setOnClickListener(this);
        modify.setOnClickListener(this);
        query.setOnClickListener(this);
        update.setOnClickListener(this);

    }

    @Override
    protected void onResume() {
        super.onResume();

        mList.clear();
        mList.addAll(mySqliteHelper.queryAllPersonData());
        Log.e(TAG, "" + mList.size());
        mAdapter.notifyDataSetChanged();

    }

    private void loadImg() {
        picArray = new byte[imgArray.length][];

        for (int i = 0; i < imgArray.length; i++) {

            picArray[i] = picTobyte(imgArray[i]);
        }
    }


    /**
     * @param resourceID  图片资源id
     * @return   将图片转化成byte
     */
    private byte[] picTobyte(int resourceID)
    {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        InputStream is = context.getResources().openRawResource(resourceID);
        Bitmap bitmap = BitmapFactory.decodeStream(is);
        //压缩图片,100代表不压缩(0~100)
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);

        return baos.toByteArray();
    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.add:

                addDataReturnID();
//                addData();
//                addDataSql();

                break;
            case R.id.delete:

                if (mList == null || mList.size() == 0) {
                    ToastUtils.show(context, "请先添加数据");
                    return;
                }

                mySqliteHelper.deletePersonData(mList.get(0));
//                mySqliteHelper.deletePersonDataSql(new PersonModel());
                notifyData();


                ToastUtils.show(context, "删除第一条数据成功");


                break;
            case R.id.modify:

                if (mList == null || mList.size() == 0) {
                    ToastUtils.show(context, "请先添加数据");
                    return;
                }

                PersonModel model = getPersonModel();
                model.setId(mList.get(0).getId());
                mySqliteHelper.updatePersonData(model);
//                mySqliteHelper.updatePersonDataSql(getPersonModel());

                ToastUtils.show(context, "修改第一条数据成功");

                notifyData();

                break;
            case R.id.query:

                if (mList == null || mList.size() == 0) {
                    ToastUtils.show(context, "请先添加数据");
                    return;
                }

                mList.clear();
                mList.addAll(mySqliteHelper.queryAllPersonDataOrderBy());
//                mList.addAll(mySqliteHelper.rawQueryAllPersonData());
                mAdapter.notifyDataSetChanged();

                break;
            case R.id.update:

                //增加版本号来更新数据库
//                mySqliteHelper = new MySqliteHelper(context, Constants.DB_NAME, null, ++currentVersion);
//                Log.e(TAG, " currentVersion = "+currentVersion );

                break;
        }


    }

    /**
     * 添加数据
     */
    private void addData() {

        PersonModel model = new PersonModel();
        model.setAddress(addressArray[mRandom.nextInt(addressArray.length)]);
        model.setName(nameArray[mRandom.nextInt(nameArray.length)]);
        model.setAge(mRandom.nextInt(101));
        model.setIsBoy(isBoyArray[mRandom.nextInt(isBoyArray.length)]);
        model.setPic(picArray[mRandom.nextInt(picArray.length)]);

        boolean isSucc = mySqliteHelper.addPersonData(model);

        if (isSucc) {

            ToastUtils.show(context, "添加数据成功");
            mList.add(0, model);
            mAdapter.notifyDataSetChanged();
        } else {
            ToastUtils.show(context, "添加失败");
        }
    }

    /**
     * 添加数据返回id
     */
    private void addDataReturnID() {

        PersonModel model = new PersonModel();
        model.setAddress(addressArray[mRandom.nextInt(addressArray.length)]);
        model.setName(nameArray[mRandom.nextInt(nameArray.length)]);
        model.setAge(mRandom.nextInt(101));
        model.setIsBoy(isBoyArray[mRandom.nextInt(isBoyArray.length)]);
        model.setPic(picArray[mRandom.nextInt(picArray.length)]);

        model = mySqliteHelper.addPersonDataReturnID(model);

        if (model != null) {

            ToastUtils.show(context, "添加数据成功");
            mList.add(0, model);
            mAdapter.notifyDataSetChanged();
        } else {
            ToastUtils.show(context, "添加失败");
        }
    }

    /**
     * 用sql语句添加数据
     */
    private void addDataSql() {

        PersonModel model = new PersonModel();
        model.setAddress(addressArray[mRandom.nextInt(addressArray.length)]);
        model.setName(nameArray[mRandom.nextInt(nameArray.length)]);
        model.setAge(mRandom.nextInt(101));
        model.setIsBoy(isBoyArray[mRandom.nextInt(isBoyArray.length)]);
        model.setPic(picArray[mRandom.nextInt(picArray.length)]);

        mySqliteHelper.addPersonDataSql(model);
        mList.add(0, model);
        mAdapter.notifyDataSetChanged();
    }

    /**
     * @return 生成一个随机的PersonModel
     */
    private PersonModel getPersonModel() {
        PersonModel model = new PersonModel();
        model.setAddress(addressArray[mRandom.nextInt(addressArray.length)]);
        model.setName(nameArray[mRandom.nextInt(nameArray.length)]);
        model.setAge(mRandom.nextInt(101));
        model.setIsBoy(isBoyArray[mRandom.nextInt(isBoyArray.length)]);
        model.setPic(picArray[mRandom.nextInt(picArray.length)]);

        return model;



    }


    /**
     * @param min
     * @param max
     * @return 随机几到几
     */
    private int randomNum(int min, int max) {
        if (min > max) {
            int temp = min;
            min = max;
            max = temp;
        }

        //专为此类设计
        max = max - 1;

        int r = Math.abs(max - min) + 1;

        return mRandom.nextInt(r) + min;
    }


    private void notifyData() {
        mList.clear();
        mList.addAll(mySqliteHelper.queryAllPersonData());
        mAdapter.notifyDataSetChanged();

    }
}

activity布局代码

<?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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.uyac.andriodsqlite.MainActivity">


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:autoLink="web"
        android:text="增删改查 需要自己去调用特定的方法,在MySqliteHelper类里面,同时需要屏蔽其他操作方法\nhttps://github.com/zhuzhushang/AndriodSqlite"
        />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >

        <Button
            android:id="@+id/add"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_margin="5dp"
            android:text="增"
            />

        <Button
            android:id="@+id/delete"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_margin="5dp"
            android:text="删"
            />

        <Button
            android:id="@+id/modify"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_margin="5dp"
            android:text="改"
            />

        <Button
            android:id="@+id/query"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_margin="5dp"
            android:text="查id↑↓"
            />

        <Button
            android:id="@+id/update"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:visibility="gone"
            android:layout_margin="5dp"
            android:text="更新"
            />

    </LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </android.support.v7.widget.RecyclerView>

</LinearLayout>

adapter代码

package com.uyac.andriodsqlite;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

/**
 * Created by ShaoQuanwei on 2017/2/14.
 */

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {

    private Context context;
    private List<PersonModel> list;

    public RecyclerAdapter(Context context, List<PersonModel> list) {
        this.context = context;
        this.list = list;
    }

    public void setList(List<PersonModel> list) {
        this.list = list;
    }

    @Override
    public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(context).inflate(R.layout.item_person, null);
        RecyclerAdapter.ViewHolder viewHolder = new RecyclerAdapter.ViewHolder(view);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerAdapter.ViewHolder holder, int position) {

        PersonModel model = list.get(position);
        holder.name.setText("名字:" + model.getName() + "(" + model.getId()+")");
        holder.address.setText("地址:" + model.getAddress());
        if (model.getIsBoy() == 1) {
            holder.sex.setText("性别:男");
        } else {
            holder.sex.setText("性别:女");
        }
        holder.age.setText("年龄:" + model.getAge());

//        ByteArrayInputStream bais = new ByteArrayInputStream(model.getPic(),0,model.getPic().length);
//        holder.pic.setImageDrawable(Drawable.createFromStream(bais,"img"));
        Bitmap b = BitmapFactory.decodeByteArray(model.getPic(), 0, model.getPic().length);
        holder.pic.setImageBitmap(b);

    }

    @Override
    public int getItemCount() {
        return list != null ? list.size() : 0;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private ImageView pic;
        private TextView name;
        private TextView sex;
        private TextView age;
        private TextView address;

        public ViewHolder(View itemView) {
            super(itemView);

            pic = (ImageView) itemView.findViewById(R.id.pic);
            name = (TextView) itemView.findViewById(R.id.name);
            sex = (TextView) itemView.findViewById(R.id.sex);
            age = (TextView) itemView.findViewById(R.id.age);
            address = (TextView) itemView.findViewById(R.id.address);

        }
    }
}

数据库代码

package com.uyac.andriodsqlite;

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

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ShaoQuanwei on 2017/2/15.
 */

public class MySqliteHelper extends SQLiteOpenHelper {

    private String TAG = "MySqliteHelper";

    /*表名*/
    private final String TABLE_NAME_PERSON = "person";
    /*id字段*/
    private final String VALUE_ID = "_id";
    private final String VALUE_NAME = "name";
    private final String VALUE_ISBOY = "isboy";
    private final String VALUE_AGE = "age";
    private final String VALUE_ADDRESS = "address";
    /*头像字段*/
    private final String VALUE_PIC = "pic";

    /*创建表语句 语句对大小写不敏感 create table 表名(字段名 类型,字段名 类型,…)*/
    private final String CREATE_PERSON = "create table " + TABLE_NAME_PERSON + "(" +
            VALUE_ID + " integer primary key," +
            VALUE_NAME + " text ," +
            VALUE_ISBOY + " integer," +
            VALUE_AGE + " ingeter," +
            VALUE_ADDRESS + " text," +
            VALUE_PIC + " blob" +
            ")";


    public MySqliteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);

        Log.e(TAG, "-------> MySqliteHelper");
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        //创建表
        db.execSQL(CREATE_PERSON);

        Log.e(TAG, "-------> onCreate");
    }

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

        Log.e(TAG, "-------> onUpgrade");

    }


    /**
     * @param model 数据模型
     * @return 返回添加数据有木有成功
     */
    public boolean addPersonData(PersonModel model) {
        //把数据添加到ContentValues
        ContentValues values = new ContentValues();
        values.put(VALUE_NAME, model.getName());
        values.put(VALUE_AGE, model.getAge());
        values.put(VALUE_ISBOY, model.getIsBoy());
        values.put(VALUE_ADDRESS, model.getAddress());
        values.put(VALUE_PIC, model.getPic());

        //添加数据到数据库
        long index = getWritableDatabase().insert(TABLE_NAME_PERSON, null, values);

        //大于0表示添加成功
        if (index > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 添加数据
     * @param model 数据模型
     * @return 返回添加数据有木有成功
     */
    public PersonModel addPersonDataReturnID(PersonModel model) {
        //把数据添加到ContentValues
        ContentValues values = new ContentValues();
        values.put(VALUE_NAME, model.getName());
        values.put(VALUE_AGE, model.getAge());
        values.put(VALUE_ISBOY, model.getIsBoy());
        values.put(VALUE_ADDRESS, model.getAddress());
        //这里存储图片,model.getPic() 是一个字节数组
        values.put(VALUE_PIC, model.getPic());

        //添加数据到数据库
        long index = getWritableDatabase().insert(TABLE_NAME_PERSON, null, values);

        //不等于-1表示添加成功(可以看insert源码)
//    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;
//        }
//    }
        if (index != -1) {
            model.setId(index);
            return model;
        } else {
            return null;
        }
    }

    /**
     * sql语句添加数据,比较麻烦
     */
    public void addPersonDataSql(PersonModel model) {

        //格式: insert into 表名 (字段名,字段名,…)value('字段值','字段值','…')
        //看着很多,其实就是这个 insert into person (name,age,isboy,address,pic) values('五天','3','0','上海市浦东新区x606','[B@5340395')
        String insertSql = "insert into " + TABLE_NAME_PERSON + " (" +
                VALUE_NAME + "," +
                VALUE_AGE + "," +
                VALUE_ISBOY + "," +
                VALUE_ADDRESS + "," +
                VALUE_PIC + ")" +
                " values" + "(" +
                "'" + model.getName() + "'," +
                "'" + model.getAge() + "'," +
                "'" + model.getIsBoy() + "'," +
                "'" + model.getAddress() + "'," +
                "'" + model.getPic() + "'" +
                ")";

        Log.e(TAG, "" + insertSql);

        getWritableDatabase().execSQL(insertSql);

    }


    /**
     * 方法删除数据库数据
     */
    public void deletePersonData(PersonModel model) {
        //where后跟条件表达式 =,!=,>,<,>=,<=
        //多条件  and or

        //删除数据库里的model数据 因为_id具有唯一性。
        getWritableDatabase().delete(TABLE_NAME_PERSON, VALUE_ID + "=?", new String[]{"" + model.getId()});
        /*//删除数据库里 _id = 1 的数据
        getWritableDatabase().delete(TABLE_NAME_PERSON,VALUE_ID+"=?",new String[]{"1"});
        //删除 age >= 18 的数据
        getWritableDatabase().delete(TABLE_NAME_PERSON,VALUE_AGE+">=?",new String[]{"18"});
        //删除 id > 5 && age <= 18 的数据
        getWritableDatabase().delete(TABLE_NAME_PERSON,VALUE_ID+">?"+" and "+VALUE_AGE +"<=?",new String[]{"5","18"});
        //删除 id > 5 || age <= 18 的数据
        getWritableDatabase().delete(TABLE_NAME_PERSON,VALUE_ID+">?"+" or "+VALUE_AGE +"<=?",new String[]{"5","18"});
        //删除数据库里 _id != 1 的数据
        getWritableDatabase().delete(TABLE_NAME_PERSON,VALUE_ID+"!=?",new String[]{"1"});
        //删除所有 _id >= 7 的男生
        getWritableDatabase().delete(TABLE_NAME_PERSON,VALUE_ISBOY+"=?"+" and "+VALUE_ID+">=?",new String[]{"1","7"});
        //删除所有 _id >= 7 和 _id = 3 的数据
        getWritableDatabase().delete(TABLE_NAME_PERSON,VALUE_ID+">=?"+" or "+VALUE_ID+"=?",new String[]{"7","3"});*/

    }

    /**
     * sql删除数据库数据
     */
    public void deletePersonDataSql(PersonModel model) {
        //条件表达式 =,!=,>,<,>=,<=
        //语法格式 delete from 表名 where 字段 条件表达式 '值'
        //语法示例 delete from person where _id='2'

        //多条件 delete from person where _id>'10' and age>'100'
        //多条件 delete from person where _id>'10' or _id<'5'

        //删除数据库里的model数据 因为_id具有唯一性。
        String sql1 = "delete from " + TABLE_NAME_PERSON + " where " +
                VALUE_ID + "=" + "'" + model.getId() + "'";
        //删除数据库里 _id = 1 的数据
        String sql2 = "delete from " + TABLE_NAME_PERSON + " where " +
                VALUE_ID + "=" + "'" + 1 + "'";
        //删除 age >= 18 的数据
        String sql3 = "delete from " + TABLE_NAME_PERSON + " where " +
                VALUE_AGE + ">=" + "'" + 18 + "'";
        //删除 id > 5 && age <= 18 的数据
        String sql4 = "delete from " + TABLE_NAME_PERSON + " where " +
                VALUE_ID + ">" + "'" + 5 + "'" + " and " +
                VALUE_AGE + "<=" + "'" + 18 + "'";
        ////删除 id > 5 || age <= 18 的数据
        String sql5 = "delete from " + TABLE_NAME_PERSON + " where " +
                VALUE_ID + ">" + "'" + 5 + "'" + " or " +
                VALUE_AGE + "<=" + "'" + 18 + "'";
        //删除数据库里 _id != 1 的数据
        String sql6 = "delete from " + TABLE_NAME_PERSON + " where " +
                VALUE_ID + "!=" + "'" + 1 + "'";
        //删除所有 _id >= 7 的男生
        String sql7 = "delete from " + TABLE_NAME_PERSON + " where " +
                VALUE_ID + ">=" + "'" + 7 + "'" + " and " +
                VALUE_ISBOY + "=" + "'" + 1 + "'";
        //删除所有 _id >= 7 和 _id = 3 的数据
        String sql8 = "delete from " + TABLE_NAME_PERSON + " where " +
                VALUE_ID + ">=" + "'" + 7 + "'" + " and " +
                VALUE_ID + "=" + "'" + 3 + "'";


        Log.e(TAG, "" + sql7);
        getWritableDatabase().execSQL(sql7);
    }


    /**
     * 方法修改数据库数据
     */
    public void updatePersonData(PersonModel model) {
        //条件表达式 =,!=,>,<,>=,<=
        //多条件 and or  and和or都可以无限连接
        //多条件示例 _id>=? and _id<=?
        //多条件示例 _id>=? or _id=? or _id=?

        //将数据添加至ContentValues
        ContentValues values = new ContentValues();
        values.put(VALUE_NAME, model.getName());
        values.put(VALUE_ADDRESS, model.getAddress());
        values.put(VALUE_ISBOY, model.getIsBoy());
        values.put(VALUE_AGE, model.getAge());
        values.put(VALUE_PIC, model.getPic());

        //修改model的数据
        getWritableDatabase().update(TABLE_NAME_PERSON, values, VALUE_ID + "=?", new String[]{"" + model.getId()});
        /*//将 _id>20 的数据全部修改成model  适合重置数据
        getWritableDatabase().update(TABLE_NAME_PERSON,values,VALUE_ID+">?",new String[]{"20"});
        //将 _id>=30 && _id<=40 的数据全部修改成model  适合重置数据
        getWritableDatabase().update(TABLE_NAME_PERSON,values,VALUE_ID+">=? and "+VALUE_ID+"<=?",new String[]{"30","40"});
        //将 _id>=40 || _id=30 || _id=20的 age 修改成18 (需先将model的数据修成成18) 这里and 和 or 的效果时一样的 因为_id是唯一的
        int count = getWritableDatabase().update(TABLE_NAME_PERSON,values,VALUE_ID+">=?"+" or "+VALUE_ID+"=?"+" or "+VALUE_ID+"=?",new String[]{"40","30","20"});*/

        // count 返回被修改的条数  >0 表示修改成功
        Log.e(TAG, "" + VALUE_ID + ">=? and " + VALUE_ID + "<=?");
        Log.e(TAG, "" + VALUE_ID + ">=?" + " or " + VALUE_ID + "=?" + " or " + VALUE_ID + "=?");

    }

    /**
     * sql修改数据库数据
     */
    public void updatePersonDataSql(PersonModel model) {
        //条件表达式 =,!=,>,<,>=,<=
        //多条件 and or  and和or都可以无限连接

        //修改格式 update 表名 set 字段='字段值', 字段='字段值',… where 字段='字段值'
        //多条件示例 update person set name='钢铁侠',isboy='1' where _id='2'
        //多条件示例 update person set name='天地',isboy='1',age='79',address='山东省青岛市开平路53号国棉四厂二宿舍1号楼2单元204户甲',pic='[B@266d768b' where _id>='30' and _id<='40'
        //多条件示例 update person set name='小二',isboy='1',age='18',address='河南南阳市八一路272号特钢公司',pic='[B@17560c26' where _id>='40' or _id='30' or _id='20'


        //修改model的数据
        String update1 = "update " + TABLE_NAME_PERSON + " set " +
                VALUE_NAME + "=" + "'" + model.getName() + "'," +
                VALUE_ISBOY + "=" + "'" + model.getIsBoy() + "'," +
                VALUE_AGE + "=" + "'" + model.getAge() + "'," +
                VALUE_ADDRESS + "=" + "'" + model.getAddress() + "'," +
                VALUE_PIC + "=" + "'" + model.getPic() + "'" + " where " +
                VALUE_ID + "=" + "'" + model.getId() + "'";

        //将 _id>20 的数据全部修改成model  适合重置数据
        String update2 = "update " + TABLE_NAME_PERSON + " set " +
                VALUE_NAME + "=" + "'" + model.getName() + "'," +
                VALUE_ISBOY + "=" + "'" + model.getIsBoy() + "'," +
                VALUE_AGE + "=" + "'" + model.getAge() + "'," +
                VALUE_ADDRESS + "=" + "'" + model.getAddress() + "'," +
                VALUE_PIC + "=" + "'" + model.getPic() + "'" + " where " +
                VALUE_ID + ">=" + "'" + "20" + "'";

        //将 _id>=30 && _id<=40 的数据全部修改成model  适合重置数据
        String update3 = "update " + TABLE_NAME_PERSON + " set " +
                VALUE_NAME + "=" + "'" + model.getName() + "'," +
                VALUE_ISBOY + "=" + "'" + model.getIsBoy() + "'," +
                VALUE_AGE + "=" + "'" + model.getAge() + "'," +
                VALUE_ADDRESS + "=" + "'" + model.getAddress() + "'," +
                VALUE_PIC + "=" + "'" + model.getPic() + "'" + " where " +
                VALUE_ID + ">=" + "'" + "30" + "'" + " and " +
                VALUE_ID + "<=" + "'" + "40" + "'";

        //将 _id>=40 || _id=30 || _id=20的 age 修改成18 (需先将model的数据修成成18) 这里and 和 or 的效果时一样的 因为_id是唯一的
        String update4 = "update " + TABLE_NAME_PERSON + " set " +
                VALUE_NAME + "=" + "'" + model.getName() + "'," +
                VALUE_ISBOY + "=" + "'" + model.getIsBoy() + "'," +
                VALUE_AGE + "=" + "'" + "18" + "'," +
                VALUE_ADDRESS + "=" + "'" + model.getAddress() + "'," +
                VALUE_PIC + "=" + "'" + model.getPic() + "'" + " where " +
                VALUE_ID + ">=" + "'" + "40" + "'" + " or " +
                VALUE_ID + "=" + "'" + "30" + "'" + " or " +
                VALUE_ID + "=" + "'" + "20" + "'";

        //其实前面set语句都一样,后面的where 不一样

        Log.e(TAG, "" + update1);
        Log.e(TAG, "" + update4);
        ;
        getWritableDatabase().execSQL(update4);

    }

    private boolean order_by;

    /**
     * 查询全部数据
     */
    public List<PersonModel> queryAllPersonData() {

        //查询全部数据
        Cursor cursor = getWritableDatabase().query(TABLE_NAME_PERSON, null, null, null, null, null, null, null);
        List<PersonModel> list = new ArrayList<>();
        if (cursor.getCount() > 0) {
            //移动到首位
            cursor.moveToFirst();
            for (int i = 0; i < cursor.getCount(); i++) {

                int id = cursor.getInt(cursor.getColumnIndex(VALUE_ID));
                String name = cursor.getString(cursor.getColumnIndex(VALUE_NAME));
                int isBoy = cursor.getInt(cursor.getColumnIndex(VALUE_ISBOY));
                int age = cursor.getInt(cursor.getColumnIndex(VALUE_AGE));
                String address = cursor.getString(cursor.getColumnIndex(VALUE_ADDRESS));
                byte pic[] = cursor.getBlob(cursor.getColumnIndex(VALUE_PIC));

                PersonModel model = new PersonModel();
                model.setId(id);
                model.setName(name);
                model.setIsBoy(isBoy);
                model.setAge(age);
                model.setAddress(address);
                model.setPic(pic);

                list.add(model);
                //移动到下一位
                cursor.moveToNext();
            }
        }

        cursor.close();
        getWritableDatabase().close();

        return list;
    }

    /**
     * 查询全部数据,按id降序或者升序排列。
     */
    public List<PersonModel> queryAllPersonDataOrderBy() {

        order_by = !order_by;
        //查询全部数据
        Cursor cursor = getWritableDatabase().query(TABLE_NAME_PERSON, null, null, null, null, null, order_by ? VALUE_ID + " desc" : VALUE_ID + " asc", null);
        List<PersonModel> list = new ArrayList<>();
        if (cursor.getCount() > 0) {
            //移动到首位
            cursor.moveToFirst();
            for (int i = 0; i < cursor.getCount(); i++) {

                int id = cursor.getInt(cursor.getColumnIndex(VALUE_ID));
                String name = cursor.getString(cursor.getColumnIndex(VALUE_NAME));
                int isBoy = cursor.getInt(cursor.getColumnIndex(VALUE_ISBOY));
                int age = cursor.getInt(cursor.getColumnIndex(VALUE_AGE));
                String address = cursor.getString(cursor.getColumnIndex(VALUE_ADDRESS));
                byte pic[] = cursor.getBlob(cursor.getColumnIndex(VALUE_PIC));

                PersonModel model = new PersonModel();
                model.setId(id);
                model.setName(name);
                model.setIsBoy(isBoy);
                model.setAge(age);
                model.setAddress(address);
                model.setPic(pic);

                list.add(model);
                //移动到下一位
                cursor.moveToNext();
            }
        }

        cursor.close();
        getWritableDatabase().close();

        return list;
    }


    /**
     * query()方法查询
     * 一些查询用法
     */
    public Cursor queryPersonData() {

        Cursor cursor = null;

        //查询全部数据
        cursor = getWritableDatabase().query(TABLE_NAME_PERSON, null, null, null, null, null, null);
        //查询 _id = 1 的数据
        cursor = getWritableDatabase().query(TABLE_NAME_PERSON, null, VALUE_ID + "=?", new String[]{"1"}, null, null, null);
        //查询 name = 张三 并且 age > 23 的数据
        cursor = getWritableDatabase().query(TABLE_NAME_PERSON, null, VALUE_NAME + "=?" + " and " + VALUE_AGE + ">?", new String[]{"张三", "23"}, null, null, null);
        //查询 name = 张三 并且 age > 23 的数据  并按照id 降序排列
        cursor = getWritableDatabase().query(TABLE_NAME_PERSON, null, VALUE_NAME + "=?" + " and " + VALUE_AGE + ">?", new String[]{"张三", "23"}, null, null, VALUE_ID + " desc");
        //查询数据按_id降序排列 并且只取前4条。
        cursor = getWritableDatabase().query(TABLE_NAME_PERSON, null, null, null, null, null, VALUE_ID + " desc", "0,4");

        return cursor;
    }


    /**
     * rawQuery()方法查询
     *
     * 一些查询用法
     *
     * 容易出错,万千注意。
     *
     * 注意空格、单引号、单词不要写错了。
     *
     */
    public Cursor rawQueryPersonData() {

        Cursor cursor = null;
        String rawQuerySql = null;

        //查询全部数据
        rawQuerySql =  "select * from "+TABLE_NAME_PERSON;
        //查询_id = 1 的数据  select * from person where _id = 1
        rawQuerySql = "select * from "+TABLE_NAME_PERSON+" where "+VALUE_ID +" = 1";

        //查询 name = 张三 并且 age > 23 的数据  通配符? select * from person where name = ? and age > ?
        rawQuerySql = "select * from "+TABLE_NAME_PERSON+" where "+VALUE_NAME +" = ?"+" and "+ VALUE_AGE +" > ?";
//        cursor = getWritableDatabase().rawQuery(rawQuerySql,new String[]{"张三","23"});

        //查询 name = 张三 并且 age >= 23 的数据  select * from person where name = '张三' and age >= '23'
        rawQuerySql = "select * from "+TABLE_NAME_PERSON+" where "+VALUE_NAME +" = '张三'"+" and "+ VALUE_AGE +" >= '23'";

        //查询 name = 张三 并且 age >= 23 的数据  并按照id 降序排列  select * from person where name = '张三' and age >= '23' order by _id desc
        rawQuerySql = "select * from "+TABLE_NAME_PERSON+" where "+VALUE_NAME +" = '张三'"+" and "+ VALUE_AGE +" >= '23'"+" order by "+VALUE_ID +" desc";

        //查询数据按_id降序排列 并且只取前4条。(测试下标是从0开始)  select * from person order by _id desc limit 0, 4
        rawQuerySql = "select * from "+TABLE_NAME_PERSON+" order by "+VALUE_ID +" desc"+" limit 0, 4";

        //查询年龄在20岁以上或者是女生 的数据 select age,isboy from person where age > 20 or isboy != 1
        rawQuerySql = "select "+VALUE_AGE+","+VALUE_ISBOY +" from " +TABLE_NAME_PERSON+" where "+VALUE_AGE+" > 20"+" or "+VALUE_ISBOY +" != 1";

        //查询年龄小于等于20 或者 大于等于 80的数据 并且按年龄升序排列 select * from person where age <= 20 or age >=80 order by age asc
        rawQuerySql = "select * from "+TABLE_NAME_PERSON+" where "+VALUE_AGE+" <= 20"+" or "+VALUE_AGE+" >=80"+" order by "+VALUE_AGE+" asc";

        cursor = getWritableDatabase().rawQuery(rawQuerySql,null);

        Log.e(TAG, rawQuerySql );

        return cursor;

    }

    /**
     * 查询全部数据
     */
    public List<PersonModel> rawQueryAllPersonData() {

        //查询全部数据
        Cursor cursor = rawQueryPersonData();
        List<PersonModel> list = new ArrayList<>();
        if (cursor != null && cursor.getCount() > 0) {
            //移动到首位
            cursor.moveToFirst();
            for (int i = 0; i < cursor.getCount(); i++) {

                int id = cursor.getInt(cursor.getColumnIndex(VALUE_ID));
                String name = cursor.getString(cursor.getColumnIndex(VALUE_NAME));
                int isBoy = cursor.getInt(cursor.getColumnIndex(VALUE_ISBOY));
                int age = cursor.getInt(cursor.getColumnIndex(VALUE_AGE));
                String address = cursor.getString(cursor.getColumnIndex(VALUE_ADDRESS));
                byte pic[] = cursor.getBlob(cursor.getColumnIndex(VALUE_PIC));

                PersonModel model = new PersonModel();
                model.setId(id);
                model.setName(name);
                model.setIsBoy(isBoy);
                model.setAge(age);
                model.setAddress(address);
                model.setPic(pic);

                list.add(model);
                //移动到下一位
                cursor.moveToNext();
            }
        }

        cursor.close();
        getWritableDatabase().close();

        return list;
    }

}

model代码

package com.uyac.andriodsqlite;

/**
 * Created by ShaoQuanwei on 2017/2/14.
 */

public class PersonModel {

    private long id;
    private String name;
    /*1代表是男孩*/
    private int isBoy;
    private int age;
    private String address;
    private byte[] pic;


    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getIsBoy() {
        return isBoy;
    }

    public void setIsBoy(int isBoy) {
        this.isBoy = isBoy;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public byte[] getPic() {
        return pic;
    }

    public void setPic(byte[] pic) {
        this.pic = pic;
    }
}

item代码

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

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"

                  android:orientation="horizontal"
                  android:padding="8dp">


        <ImageView
            android:id="@+id/pic"
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:src="@mipmap/ic_launcher"

            />


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:orientation="vertical"
            >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                >

                <TextView
                    android:id="@+id/name"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="张三"
                    />

                <TextView
                    android:id="@+id/sex"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="性别:男"

                    />
            </LinearLayout>

            <TextView
                android:id="@+id/age"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:text="年龄:17"
                />

            <TextView
                android:id="@+id/address"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:text="深圳市南山区深南大道10000号"
                />

        </LinearLayout>


    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="0.6dp"
        android:background="@color/colorAccent"
        />

</LinearLayout>

目录结构

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,236评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,867评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,715评论 0 340
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,899评论 1 278
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,895评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,733评论 1 283
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,085评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,722评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,025评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,696评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,816评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,447评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,057评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,009评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,254评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,204评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,561评论 2 343

推荐阅读更多精彩内容