SQLite的使用笔记

简介

SQLite 是一个小型的、可嵌入的关系型数据库,是一个开源的数据库。SQLite的系统开销非常小,体积小,检索效率非常高。不需要专门的数据库引擎来做支持。详细的大家找度娘再仔细了解,这里就不做详细介绍了。

特点

  • 是一个独立的跨平台的磁盘文件
  • 代码量非常少
  • api简单易用

在Android中创建SQLite数据库

首先我们需要创建一个SQLiteHelper类,这个类继承了SQLiteOpenHelper基类

public class MySQLiteHelper extends SQLiteOpenHelper {

    private final String TAG=this.getClass().getName();

    public MySQLiteHelper(Context context) {
        super(context, Constant.DATABASE_NAME, null, Constant.DATABASE_VERSION);
    }

    /**
     * 构造函数
     * @param context 上下文对象
     * @param name 要创建的数据库名称
     * @param factory 游标工厂
     * @param version 数据库版本
     */
    public MySQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    /**
     * 创建数据路是的回调
     * @param db 数据库的对象
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.i(TAG, "------------onCreate---------------");
        //创建表
        db.execSQL(Constant.CREATE_PERSON);
    }

    /**
     * 数据库有版本更新时的回调函数
     * @param db 数据库对象
     * @param oldVersion 数据库旧版本
     * @param newVersion 数据库新版本
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.i(TAG, "-------------------onUpgrade------------------");
    }

    /**
     * 数据库打开时的回调函数
     * @param db 数据库对象
     */
    @Override
    public void onOpen(SQLiteDatabase db) {
        super.onOpen(db);
        Log.i(TAG, "-----------------------onOpen------------------------");
    }

然后创建一个管理类,实现单例模式

public class DBManager {
    private static MySQLiteHelper helper;

    public static MySQLiteHelper getInstace(Context context){
        if (helper == null) {
            helper = new MySQLiteHelper(context);
        }
        return helper;
    }
}

然后再创建一个常量类,方便后边使用和防止手写sql时出错

public class Constant {
    public static final String DATABASE_NAME = "info.db";//数据库的名称
    public static final int DATABASE_VERSION = 1;//数据库的版本
    public static final String TABLE_NAME = "Person";//表名
    //表中的一些字段
    public static final String _ID = "_id";
    public static final String NAME = "name";
    public static final String AGE = "age";

    //创建表的SQL语句
    public static final String CREATE_PERSON = "create table " + TABLE_NAME + " (" +
                                                    _ID + " Integer primary key," +
                                                    NAME + " varchar(10)," +
                                                    AGE + " Integer)";

}
MySQLiteHelper helper = helper = DBManager.getInstace(this);
//如果数据库已存在则返回一个可读可写的数据库,如果数据库还不存在,则创建一个可读可写的数据库
SQLiteDatabase db=helper.getWritableDatabase();

当获取db对象时,就会执行MySQLiteHelper 中的onCeate回调创建数据库。至此数据库创建成功

插入数据

DBManager中添加静态方法

/**
     * 根据SQL语句在数据库中执行语句
     * @param db 数据库对象
     * @param sql sql语句
     */
    public static void execSQL(SQLiteDatabase db, String sql) {
        if (db != null) {
            if (sql != null && !"".equals(sql)) {
                db.execSQL(sql);
            }
        }
    }
  • SQL语句插入
SQLiteDatabase db = helper.getWritableDatabase();
String sql = "insert into " + Constant.TABLE_NAME + " values(" + i + ",'CrazyLiuXP" + i + "',20)";
DBManager.execSQL(db, sql);
db.close();//使用完之后一定要关闭,放置资源的占用
  • API方法插入
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Constant._ID, 1);
values.put(Constant.NAME, "张三");
values.put(Constant.AGE, 21);
 /**
 * String table, String nullColumnHack, ContentValues values
 * String table 表示插入数据表的名称
 * String nullColumnHack 选项:null或者指定的列
 *      因为SQLite不允许插入整条为空的数据
 *      null表示后边values所有列为空时不会有全部为空的数据插入
 *      不为null时表示指定的列数据允许为空
 * ContentValues values是一个键值对
 * 返回值 long 标识sql语句作用的条目数
 */
long result = db.insert(Constant.TABLE_NAME, null, values);
if (result > 0) {
      Toast.makeText(this, "插入数据成功", Toast.LENGTH_SHORT).show();
}
db.close();

更改数据

  • SQL语句更改
SQLiteDatabase  db = helper.getWritableDatabase();
String updateSql = "update " + Constant.TABLE_NAME + " set " + Constant.NAME + "='crazy where _id = 1'";
DBManager.execSQL(db,updateSql);
db.close();
  • API方法更改
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Constant.NAME, "张三");
values.put(Constant.AGE, 100);
String selection = Constant._ID + "=?";//?标识占位符
String[] selectionArgs = {"1"};//占位符的数据
 int resultupdate = db.update(Constant.TABLE_NAME, values, selection, selectionArgs);
 if (resultupdate > 0) {
        Toast.makeText(this, "修改数据成功", Toast.LENGTH_SHORT).show();
 }
db.close();

删除数据

  • SQL删除数据
SQLiteDatabase  db = helper.getWritableDatabase();
String deleteSql = "delete from " + Constant.TABLE_NAME + " where " + Constant._ID + "=1";
DBManager.execSQL(db, deleteSql);
db.close();
  • API删除
SQLiteDatabase db = helper.getWritableDatabase();
int r= db.delete(Constant.TABLE_NAME, Constant._ID + "=?", new String[]{"1"});
 if (r > 0) {
      Toast.makeText(this, "删除数据成功", Toast.LENGTH_SHORT).show();
 }else {
      Toast.makeText(this, "删除数据失败", Toast.LENGTH_SHORT).show();
 }
db.close();

查询语句

DBManager添加方法

    /**
     * sql语句查询
     * @param db 数据库对象
     * @param sql sql语句
     * @param args 占位符数据
     * @return 返回一个游标
     */
    public static Cursor selectDataBySQL(SQLiteDatabase db,String sql,String[] args) {
        Cursor cursor = null;
        if (db != null) {
            cursor = db.rawQuery(sql, args);
        }
        return cursor;
    }

    /**
     * 把Cursor转换成List对象
     * @param cursor 游标
     * @return 返回一个list数据对象
     */
    public static List cursorToList(Cursor cursor) {
        List list = new ArrayList<>();
        while (cursor.moveToNext()) {
            int id = cursor.getInt(cursor.getColumnIndex(Constant._ID));
            String name = cursor.getString(cursor.getColumnIndex(Constant.NAME));
            int age = cursor.getInt(cursor.getColumnIndex(Constant.AGE));
            Person person = new Person(id, name, age);
            list.add(person);
        }
        return list;
    }
  • SQL语句查询
SQLiteDatabase db = helper.getReadableDatabase();
String sql = "select * from " + Constant.TABLE_NAME ;
Cursor cursor = DBManager.selectDataBySQL(db, sql, null);
List list = DBManager.cursorToList(cursor);
for (Person p : list) {
     Log.i(TAG, p.toString());
}
db.close();
  • API方法查询
SQLiteDatabase  db = helper.getReadableDatabase();
Cursor cursor1= db.query(Constant.TABLE_NAME, null, Constant._ID + ">?", new String[]{"90"}, null, null, Constant._ID + " desc");
 List list = DBManager.cursorToList(cursor1);
for (Person p : list) {
     Log.i(TAG, p.toString());
}
db.close();

分页查询

DBManager添加方法

/**
     * 获取数据的总条数
     * @param db 数据库对象
     * @param table 表名
     * @return 返回总条数
     */
    public static int getDataCount(SQLiteDatabase db,String table) {
        int count=0;
        if (db != null) {
            Cursor cursor = db.rawQuery("select * from " + table, null);
            count=cursor.getCount();
        }
        return count;
    }

    /**
     * 获取分页数据
     * @param db 数据库对象
     * @param table 表名
     * @param currentPage 当前页
     * @param pagesize 每页显示数量
     * @return 返回一个List数组
     */
    public static List getListByCurrentPage(SQLiteDatabase db, String table, int currentPage,int pagesize) {
        int index = (currentPage - 1) * pagesize;
        Cursor cursor = null;
        if (db != null) {
            String sql = "select * from " + table + " limit ?,?";
            cursor = db.rawQuery(sql, new String[]{index + "", pagesize + ""});
        }
        return cursorToList(cursor);
    }

Activity


public class PageActivity extends AppCompatActivity {
    private ListView listView;
    private MySQLiteHelper helper;
    private int totalNum;
    private int pageSize=25;
    private int pageNum;//总页数
    private int currentPage=1;//当前页
    private List personList;
    private MyAdapter adapter;
    private boolean isDivPage;
    private SQLiteDatabase db;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page);
        listView = (ListView) findViewById(R.id.pageList);

        helper = DBManager.getInstace(this);
        db = helper.getReadableDatabase();

        totalNum = DBManager.getDataCount(db, Constant.TABLE_NAME);//获取总条数
        pageNum = (int) Math.ceil(totalNum / (double) pageSize);//获取总页数

        if (currentPage == 1) {
            personList = DBManager.getListByCurrentPage(db, Constant.TABLE_NAME, currentPage, pageSize);
        }

        adapter = new MyAdapter(this, personList);
        listView.setAdapter(adapter);

        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                //需要分页 并且页面已经停止滚动了 则加载新的数据
                // OnScrollListener.SCROLL_STATE_IDLE停止滚动
                if (isDivPage && AbsListView.OnScrollListener.SCROLL_STATE_IDLE == scrollState) {
                    if (currentPage < pageNum) {
                        currentPage++;
                        personList.addAll(DBManager.getListByCurrentPage(db, Constant.TABLE_NAME, currentPage, pageSize));
                        adapter.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                //第一条数据的索引加可见的条目数量等于总数量 则标识需要分页了
                 isDivPage= (firstVisibleItem + visibleItemCount) == totalItemCount;
            }
        });
    }

    private class MyAdapter extends BaseAdapter {
        private Context context;
        private List personList;

        public MyAdapter(Context context, List list) {
            this.context=context;
            this.personList = list;
        }

        @Override
        public int getCount() {
            return personList.size();
        }

        @Override
        public Object getItem(int position) {
            return personList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.list_item, null);
                holder = new ViewHolder();
                holder.id = (TextView) convertView.findViewById(R.id.personId);
                holder.name = (TextView) convertView.findViewById(R.id.personName);
                holder.age = (TextView) convertView.findViewById(R.id.personAge);
                convertView.setTag(holder);
            }else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.id.setText(personList.get(position).get_id()+"");
            holder.name.setText(personList.get(position).getName());
            holder.age.setText(personList.get(position).getAge()+"");

            return convertView;
        }
    }

    class ViewHolder{
        TextView id;
        TextView name;
        TextView age;
    }
}

至此,SQLite的入门使用就记录完毕了,相信类的封装每个人都会有自己的习惯。如果有什么不对的地方欢迎指正。

你可能感兴趣的:(SQLite的使用笔记)