SQLite学习和使用

创建数据库并创建表格

1.创建MyDatabaseHelper继承于SQLiteOpenHelper(抽象类,必须实现onCreate()和onUpgrade()方法)
2.把数据库建表指令弄成一个字符串CREATE_BOOK常量,并在onCreate()函数中执行建表

public class MyDatabaseHelper extends SQLiteOpenHelper {

    //把数据库建表指令弄成一个字符串CREATE_BOOK常量
    public static final String CREATE_BOOK = "create table book ("
            + "id integer primary key autoincrement, "
            + "author text, "
            + "price real, "
            + "pages integer, "
            + "name text)";
    public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context,name,factory,version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_BOOK);//执行建表
        Log.d(TAG,"数据库初始化完成");
    }

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

3.在MianActivity()中新建数据库

    private MyDatabaseHelper dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 1);
    //新建一个MyDatabaseHelper对象,上下文;数据库名;第三个参数允许我们在查询数据的时候返回一个自定义的 Cursor,一般都是传入 null;数据库版本号
    dbHelper.getWritableDatabase();

升级数据库方法1(覆盖式)

需 求:增加一个新的表格,Category

  由于数据库BookStore.db已经存在,onCreate()方法不会再次执行,直接在onCreate()方法中,添加table不能被更新。

解决方案:使用onUpgrade()方法更新数据库

添加表格常量;在onCreate()方法中建表;在upGreate()方法中删去存在表格,并重新执行onCreate()方法;在引用数据库时更改数据库版本号

    public class MyDatabaseHelper extends SQLiteOpenHelper {

        //把数据库建表指令弄成一个字符串CREATE_BOOK常量
        public static final String CREATE_BOOK = "create table book ("
                + "id integer primary key autoincrement, "
                + "author text, "
                + "price real, "
                + "pages integer, "
                + "name text)";
        //integer 表示整型,real 表示浮点型,text 表示文本类型,blob 表示二进制类型。另外,上述建表语句中我们还
        //使用了 primary key 将 id 列设为主键,并用 autoincrement 关键字表示 id 列是自增长的

        public static final String CREATE_CATEGORY = "create table category("
                + "id integer primary key autoincrement, "
                + "category_name text, "
                + "category_code integer)";

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

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(CREATE_BOOK);//执行建表
            db.execSQL(CREATE_CATEGORY);
            Log.d(TAG,"数据库初始化完成");
        }

        //当检测到数据库版本变化,就会执行onUpgrade()中的代码
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            //调用SQL语句,若存在表格则删去,之后在重新调用onCreate()方法
            db.execSQL("drop table if exists Book");
            db.execSQL("drop table if exists Category");
            onCreate(db);
        }
    }

升级数据库方法2(追加式)

需 求:根据所需变更数据库,增加一个新的表格,Category

  由于覆盖式更新数据库的方法会重置数据库,导致用户数据丢失,不能在产品中使用


解决方案:为每一个版本号赋予它各自改变的内容,然后在onUpgrade()方法中对当前数据库的版本号进行判断,再执行相应的改变就可以了

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //调用SQL语句,若存在表格则删去,之后在重新调用onCreate()方法
        /**
         * 注释时间:20170117
         * 代码作用:覆盖式更新数据库,删除之前的数据库再新建库
         * 注释原因:学习新的数据库更新方法
        db.execSQL("drop table if exists Book");
        db.execSQL("drop table if exists Category");
        onCreate(db);
         */
        switch (newVersion)
        {
            case 2:db.execSQL(CREATE_CATEGORY);
                //!!!注意,无break;
            case 3:db.execSQL("alter table Book add column category_id integer");
                //!!!注意,无break;
                //因为无论覆盖哪一个版本安装,都需要安装其他更新,从第二版安装第三版时,只需要更新case3,确保数据库最新
                Log.d(TAG,"第3版数据库更新成功");
                break;
            default:
                Log.d(TAG,"数据库更新失败");
                break;
        }
    }

增删改查操作(SQL语句操作)

对数据进行的操作也就无非四种,即CRUD。其中 C 代表添加(Create) ,R 代表查询(Retrieve) ,U 代表更新(Update) ,D 代表删除(Delete)

SQLiteDatabase db = dbBookStoreHelper.getWritableDatabase();

    //新建两个数据
    db.execSQL("insert into Book (name, author, pages, price) values(?, ?, ?, ?)",new String[] { "The Da Vinci Code", "Dan Brown", "454", "16.96" });
    db.execSQL("insert into Book (name, author, pages, price) values(?, ?, ?, ?)",new String[] { "The Lost Symbol", "Dan Brown", "510", "19.95" });
 
    //查询所有数据
    db.rawQuery("select * from Book", null);
   
    //把《The Da Vinci Code》这本书改成10.99
    db.execSQL("update Book set price = ? where name = ?", new String[] { "10.99","The Da Vinci Code" });
  
    //把500页以上的书删了
    db.execSQL("delete from Book where pages > ?", new String[] { "500" });

增删改查操作(Android语法操作)

  • 增加数据

insert()方法,1.表名;2.未指定添加数据的情况下给某些可为空的列自动赋值 NULL;3.ContentValues 对象,它提供了一系列的 put()方法重载,用于向 ContentValues 中添加数据,只需要将表中的每个列名以及相应的待添加数据传入即可

//!!!先组装数据,再插入数据
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
// 开始组装第一条数据
values.put("name", "The Da Vinci Code");
values.put("author", "Dan Brown");
values.put("pages", 454);
values.put("price", 16.96);
db.insert("Book", null, values); // 插入第一条数据
values.clear();
// 开始组装第二条数据
values.put("name", "The Lost Symbol");
values.put("author", "Dan Brown");
values.put("pages", 510);
values.put("price", 19.95);
db.insert("Book", null, values); // 插入第二条数据
  • 更改数据

update()方法,1.表名;2.ContentValues 对象,要把更新数据在这里组装进去;第三、第四个参数用于去约束更新某一行或某几行中的数据,不指定的话默认就是更新所有行

SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("price", 10.99);
db.update("Book", values, "name = ?", new String[] { "The DaVinci Code" });
values.clean();
  • 删除数据

delete()方法,1.表名;第二、第三个参数用于去约束删除某一行或某几行的数据,不指定的话默认就是删除所有行

db.delete("Book","pages > ?",new String[] {"300"});
  • 查询数据

query()方法,1.表名;2.指定去查询哪几列,如果不指定则默认查询所有列;3.第三、第四个参数用于去约束查询某一行或某几行的数据,不指定则默认是查询所有行的数据;5.指定需要去 group by 的列,不指定则表示不对查询结果进行 group by 操作;6. group by 之后的数据进行进一步的过滤,不指定则表示不进行过滤;7,指定查询结果的排序方式,不指定则表示使用默认的排序方式。

 

query()方法参数 对应 SQL 部分   描述
table  from table_name  指定查询的表名
columns  select column1, column2  指定查询的列名
selection  where column = value  指定 where 的约束条件
selectionArgs  -  为 where 中的占位符提供具体的值
groupBy  group by column  指定需要 group by 的列
having  having column = value  对 group by 后的结果进一步约束
orderBy  order by column1, column2  指定查询结果的排序方式

 

 

Cursor cursor = db.query("Book",null,"1",null,null,null,null);
    if (cursor != null)
    {
        if(cursor.moveToFirst())
        {
            do {//直到型循环
                String name = cursor.getString(cursor.getColumnIndex("name"));
                String author = cursor.getString(cursor.getColumnIndex("author"));
                Double price = cursor.getDouble(cursor.getColumnIndex("price"));
                int pages = cursor.getInt(cursor.getColumnIndex("pages"));
                Log.d(TAG,"name = " + name);
                Log.d(TAG,"author = " + author);
                Log.d(TAG,"price = " + price);
                Log.d(TAG,"pages = " + pages);
            }while (cursor.moveToNext());
        }
    }
    cursor.close();

 

使用事务Transaction

事情要有始有终,就像转账,钱没到达对方账户就会退回原始账户


需 求:删除旧的数据库,更换新的数据库

解决方案:使用beginTransaction,setTransactionSuccessful,endTransaction三个来监控事务的执行,一旦执行失败,返回原始的数据库

    db.beginTransaction();//开始事务
    try {
        db.delete("Book", null, null);
        if (true) {
            // 在这里手动抛出一个异常,让事务失败
            throw new NullPointerException();
        }
        db.execSQL("insert into Book (name, author, pages, price) values(?, ?, ?, ?)",
                new String[]{"马克思主义2", "中国**党", "1000", "100.00"});//居然和谐
        db.setTransactionSuccessful(); // 事务已经执行成功
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        db.endTransaction(); // 结束事务
    }
岑忠满的博客新站点 https://cenzm.xyz
原文地址:https://www.cnblogs.com/cenzhongman/p/6392753.html