SQLite的一些基本操作

先声明,这篇文章也是以前写的,这里只是把该文章从另一个账号搬过来

关于SQLite使用其实并没有什么难点,感觉主要是有时候可能长时间不用会对其创建数据库以及增删改查的一些语法容易忘记,而每当要使用的时候都需要去查资料,而且还不能保证立马就查到自己想要的,所以就决定写这篇文章,记录一下SQLite的创建以及增删改查的一些基本语句,以便日后需要的时候可以第一时间找到自己想要的资料,而且自己记录一遍更能加深印象,所以有时间的话建议大家都可以写写博客,坚持下来,还是会有很大收获的。

1. 什么情况下使用SQLite数据库存储 ?

关于SQLite存储数据,我之前一直比较疑惑,也没有去深究过,到底使用SQLite存储数据有什么优势。现在个人觉得使用SQLite存储的好处主要是可以实现查询功能,比如我们做一个便签APP,把写的内容存储在SQLite中,就可以实现模糊查询查找自己想要的内容。还有对于数据较多的也可以使用SQLite存储,对于一些方便以表形式存储的数据用SQLite存储也很方便,目前而言自己发现的优点主要有这几点。如果有不正确或者还有其他的优点欢迎各位大佬指出。

2. 如何创建一个SQLite数据库 ?

创建SQLite数据库有三种方式:

  1. 继承SQLiteOpenHelper
  2. Context.openOrCreateDatabase()
  3. SQLiteDatabase.openOrCreateDatabase()

接下来看一下这三种方式的实现代码:

2.1 继承SQLiteOpenHelper(优点:可以在升级数据库版本的时候在回调函数里面做相应的操作)
public class MySQLiteOpenHelper extends SQLiteOpenHelper {

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

    //自定义构造器
    public MySQLiteOpenHelper(Context context,String name){
        this(context,name,null,1);
    }

    /**
     * Const.TABNAME(表名)  content(字段名)  id(主键)
     * @param db
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        //在创建数据库时,创建一个数据表table
        String sql = "create table if not exists "+Const.TABNAME+"(id integer primary key  autoincrement,content text,time text )";
        db.execSQL(sql);
    }

    /**
     * 数据库升级更新时调用
     * @param db
     * @param oldVersion
     * @param newVersion
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

创建好了数据库帮助类之后我们需要用它来帮我们创建数据库,通过下面代码我们就创建好了数据库

 //创建数据库
        mMySQLiteOpenHelper = new MySQLiteOpenHelper(getApplicationContext(), "note.db");
        mSqLiteDatabase = mMySQLiteOpenHelper.getWritableDatabase();
2.2 Context.openOrCreateDatabase()(优点:可以指定数据库文件的操作模式)

代码如下:

/**指定数据库的名称为note.db,并指定数据文件的操作模式为MODE_PRIVATE**/
        SQLiteDatabase sqLiteDatabase = this.openOrCreateDatabase("note.db", MODE_PRIVATE, null);
2.3 SQLiteDatabase.openOrCreateDatabase()(优点:可以指定数据库文件的路径)

注意:这种方式就可以把我们的数据库保存的外部文件里(如SD卡上),曾经面试就被问到过。接下来看下代码:

 File dataBaseFile = new File(Environment.getExternalStorageDirectory() + "/sqlite", "note.db");
        if (!dataBaseFile.getParentFile().exists()) {
            dataBaseFile.mkdirs();
        }
        SQLiteDatabase sqLiteDatabase = SQLiteDatabase.openOrCreateDatabase(dataBaseFile, null);
3. SQLite的增删改查语句 ?
3.1 增
    String sql = "insert into " +Const.TABNAME+ "(content,time) " +
                " values('新建笔记','2018/04/10')";
3.2 删
String sql = "delete from "+Const.TABNAME+" where id=1";
3.3 改
 //修改单个字段
        String sql = "update " +Const.TABNAME+" set content='hello java '  where id = 1";
        //修改多个字段
        String sql = "update " +Const.TABNAME+" set content='hello java ',time='2020/05/10'  where id = 1";
3.4 查
String sql= "select * from " + Const.TABNAME;
        Cursor cursor = mSqLiteDatabase.rawQuery(sql, null);
        cursor.moveToFirst();
        while (cursor.moveToNext()) {
            String content = cursor.getString(cursor.getColumnIndex("content"));
            String time = cursor.getString(cursor.getColumnIndex("time"));
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            Log.e(TAG, "数据库内容:" + id+content+time);
        }
        cursor.close();
4. 使用Android提供的API进行增删改查
4.1 增
/**
     * long insert(String table, String nullColumnHack, ContentValues values)
     * 第一个参数:数据库表名
     * 第二个参数:当values参数为空或者里面没有内容的时候,
     * insert是会失败的(底层数据库不允许插入一个空行),
     * 为了防止这种情况,要在这里指定一个列名,
     * 到时候如果发现将要插入的行为空行时,
     * 就会将你指定的这个列名的值设为null,然后再向数据库中插入。
     * 第三个参数:要插入的值
     * 返回值:成功操作的行号,错误返回-1
     */
ContentValues contentValues = new ContentValues();
        contentValues.put("content","hello my name is xiaochao");
        contentValues.put("time","2018年4月10日");
        long num = mSqLiteDatabase.insert(Const.TABNAME,null,contentValues);
        if (num == -1) {
            Toast.makeText(this, "插入失败", Toast.LENGTH_SHORT).show();
        }
4.2 删
 /**
         * int delete(String table, String whereClause, String[] whereArgs)
         * 第一个参数:删除的表名
         * 第二个参数:修改的条件的字段
         * 第三个参数:修改的条件字段对应的值
         * 返回值:影响的行数
         * 下面两行代码实现的功能是一样的
         */
    //   int num =  mSqLiteDatabase.delete(Const.TABNAME,"id=1",null);
       int num = mSqLiteDatabase.delete(Const.TABNAME,"id=?",new String[]{"1"});
4.3 改
ContentValues contentValues = new ContentValues();
        contentValues.put("content","hello ,this is update data");
        contentValues.put("time","2017/10/8");
//         int num =  mSqLiteDatabase.update(Const.TABNAME,contentValues,"id=7",null);
         int num  = mSqLiteDatabase.update(Const.TABNAME,contentValues,"id=?",new String[]{"7"});
4.4 查
 Cursor cursor = mSqLiteDatabase.query(Const.TABNAME,null,null,null,null,null,null);
        if(cursor==null){
            return;
        }
        cursor.moveToFirst();
        while (cursor.moveToNext()){
            String content = cursor.getString(cursor.getColumnIndex("content"));
            String time = cursor.getString(cursor.getColumnIndex("time"));
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            Log.e(TAG, "数据库内容=" + id+content+time);
        }
5. 总结

接下来还是总结一下整个流程:
1.创建数据库,有三种方式,平时一般用第一种,第一种可以直接在创建的时候创建表

  • 继承SQLiteOpenHelper
  • Context.openOrCreateDatabase()
  • SQLiteDatabase.openOrCreateDatabase()

2.如果创建数据库的时候没有创建表,先创建一张表,然后对表进行增删改查操作。
3.增删改查操作可以通过SQL语句执行,也可以使用Android提供的API去执行。
4.SQL语句执行增删改查:

  • 增:String sql = "insert into " +表名+ "(字段1,字段2) " +
    " values('字段1的值','字段2的值')";

    扫描二维码关注公众号,回复: 2902421 查看本文章
  • 删:String sql = "delete from "+表名+" where 条件(如:id=1)";

  • 改:String sql = "update " +表名+" set 字段1='字段1值 ' where 条件(如:id = 1)";
//修改多个字段
        String sql = "update " +表名+" set 字段1='字段1值',字段2='字段2值'  where 条件";
String sql= "select * from " + 表名;
        Cursor cursor = mSqLiteDatabase.rawQuery(sql, null);
        cursor.moveToFirst();
        while (cursor.moveToNext()) {
            String content = cursor.getString(cursor.getColumnIndex("字段1"));
            String time = cursor.getString(cursor.getColumnIndex("字段2"));
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            Log.e(TAG, "数据库内容:" + id+content+time);
        }
        cursor.close();

5.使用Android提供的API进行增删改查:

  • 增:
ContentValues contentValues = new ContentValues();
        contentValues.put("字段1","字段1值");
        contentValues.put("字段2","字段2值");
        long num = mSqLiteDatabase.insert(表名,null,contentValues);
        if (num == -1) {
            Toast.makeText(this, "插入失败", Toast.LENGTH_SHORT).show();
        }
 /**
         * int delete(String table, String whereClause, String[] whereArgs)
         * 第一个参数:删除的表名
         * 第二个参数:修改的条件的字段
         * 第三个参数:修改的条件字段对应的值
         * 返回值:影响的行数
         */
       int num =  mSqLiteDatabase.delete(Const.TABNAME,"id=1",null);
//       int num = mSqLiteDatabase.delete(Const.TABNAME,"id=?",new String[]{"1"});
  • 改:
 ContentValues contentValues = new ContentValues();
        contentValues.put("字段1","字段1值");
        contentValues.put("字段2","字段2值");
//         int num =  mSqLiteDatabase.update(Const.TABNAME,contentValues,"id=7",null);
         int num  = mSqLiteDatabase.update(Const.TABNAME,contentValues,"id=?",new String[]{"7"});
  • 查:
 Cursor cursor = mSqLiteDatabase.query(Const.TABNAME,null,null,null,null,null,null);
        if(cursor==null){
            return;
        }
        cursor.moveToFirst();
        while (cursor.moveToNext()){
            String content = cursor.getString(cursor.getColumnIndex("字段1"));
            String time = cursor.getString(cursor.getColumnIndex("字段2"));
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            Log.e(TAG, "数据库内容=" + id+content+time);
        }

好了,以上就是对数据库的一些基本操纵了,由于写博客时间不长,体验并不是那么好,但是这博客主要是为了方便以后忘记时可以快速查看了解,所以只是一些最基本的操作,如果觉得不够好,可以看看这个系列的文章,虽然也比较基础,但是条理还是蛮清晰的。玩转SQLite系列

猜你喜欢

转载自blog.csdn.net/xiaochao_develop/article/details/82018190