安卓SQLite基础使用指南

栏目: 数据库 · 发布时间: 5年前

内容简介:[1]熟悉MySQL的学这个就像会西瓜的人去学吃哈密瓜一样简单。[2]如果对MySQL不太熟悉的童鞋,可以看一下我的这篇[3]SQLite:安卓内置轻量级的关系型数据库

零、前言

[1]熟悉 MySQL 的学这个就像会西瓜的人去学吃哈密瓜一样简单。

[2]如果对MySQL不太熟悉的童鞋,可以看一下我的这篇 :SpringBoot-14-MyBatis预热篇,MySQL小结

[3]SQLite:安卓内置轻量级的关系型数据库

[4]强烈建议语句什么的提前写好,在MySQL上测试一下,不然少个分号,多个逗号什么的就呵呵了

[5]安卓有API支持数据库操作,但感觉不怎么灵活,感兴趣的可以自己了解一下

坑点

[1]:SQLite 不支持 DEFAULT 和 NOT NULL 连用(虽然连在一起也没啥用)
[3]:INSERT INTO 的 INTO 要加上 (MySQL养成的坏毛病,得该)

一、创建数据库

1.SQL常量类:SQLCon.java

/**
 * 作者:张风捷特烈<br/>
 * 时间:2018/8/26 0026:14:48<br/>
 * 邮箱:1981462002@qq.com<br/>
 * 说明:SQL常量类
 */
public class SQLCon {
    /**
     * 数据库名
     */
    public static String DB_NAME = "weapon";

    /**
     * 数据库版本
     */
    public static int DB_VERSION = 1;

    /**
     * 建表语句
     */
    public static final String CREATE_TABLE = "CREATE TABLE sword (\n" +
            "id SMALLINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,\n" +
            "name VARCHAR(32) NOT NULL,\n" +
            "atk SMALLINT UNSIGNED NOT NULL,\n" +
            "hit SMALLINT UNSIGNED NOT NULL DEFAULT 20,\n" +
            "crit SMALLINT UNSIGNED NOT NULL DEFAULT 10\n" +
            ");";
    
}

2.SQLiteOpenHelper使用:我的数据库辅助类

/**
 * 作者:张风捷特烈<br/>
 * 时间:2018/8/26 0026:14:26<br/>
 * 邮箱:1981462002@qq.com<br/>
 * 说明:我的数据库辅助类
 */
public class MySQLHelper extends SQLiteOpenHelper {

    private Context mContext;

    /**
     * 构造函数
     *
     * @param context 上下文
     */
    public MySQLHelper(Context context) {
        super(context, SQLCon.DB_NAME, null, SQLCon.DB_VERSION);
        mContext = context;
    }

    /**
     * 创建数据库,数据库存在就不会执行
     *
     * @param db SQLite数据库对象
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQLCon.CREATE_TABLE);//创建表
    }

    /**
     * 数据库进行升级
     *
     * @param db         SQLite数据库对象
     * @param oldVersion 旧版本
     * @param newVersion 新版本
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        
    }
}

3.在需要的地方使用:

MySQLHelper mySQLHelper = new MySQLHelper(this);//创建辅助对象
mySQLHelper.getWritableDatabase();//获取可写数据库对象

//getReadableDatabase()和getWritableDatabase()
//这两个方法都可以创建或打开一个现有的数据库,并返回一个可对数据库进行读写操作的对象。
//磁盘空间已满时getWritableDatabase()异常

安卓 <a href='https://www.codercto.com/topics/18894.html'>SQLite</a> 基础使用指南

二、升级数据库时删除表

1.SQL常量类,将数据库版本改到2:SQLCon.java

/**
     * 数据库版本
     */
    public static int DB_VERSION = 2;
    
    /**
     * 删除表语句
     */
    public static final String DROP_TABLE = "DROP TABLE sword";

2.com.toly1994.si_sqlite.MySQLHelper#onUpgrade

db.execSQL(SQLCon.DROP_TABLE);
L.d(oldVersion+":"+newVersion+L.l());//1:2

3.在需要的地方使用

MySQLHelper mySQLHelper2 = new MySQLHelper(this);//创建辅助对象
mySQLHelper2.getWritableDatabase();//获取可写数据库对象

三、数据库的常用操作(CRUD):

1.插入数据(C)

/**
     * 插入语句
     */
    public static final String INSERT = "INSERT INTO sword(id,name,atk,hit,crit) VALUES" +
            "(1,'痕兮',7000,800,999)," +
            "(2,'逐暮',100,1000,10000)," +
            "(3,'风跃',9000,10,255);";
mDb = new MySQLHelper(this).getWritableDatabase();
mDb.execSQL(SQLCon.INSERT);

安卓SQLite基础使用指南

2.删除数据

/**
     * 删除数据
     */
    public static final String DELETE = "DELETE FROM sword WHERE id=1;";
mDb = new MySQLHelper(this).getWritableDatabase();
mDb.execSQL(SQLCon.DELETE);

安卓SQLite基础使用指南

3.修改数据

/**
     * 修改数据
     */
    public static final String UPDATE = "UPDATE sword SET hit=hit+1;";
mDb = new MySQLHelper(this).getWritableDatabase();
mDb.execSQL(SQLCon.UPDATE);

安卓SQLite基础使用指南

4.查询数据

1.查询所用

Cursor cursor = mDb.rawQuery("SELECT * FROM sword", null);
while (cursor.moveToNext()) {
    String id = cursor.getString(cursor.getColumnIndex("id"));
    String name = cursor.getString(cursor.getColumnIndex("name"));
    String atk = cursor.getString(cursor.getColumnIndex("atk"));
    String hit = cursor.getString(cursor.getColumnIndex("hit"));
    String crit = cursor.getString(cursor.getColumnIndex("crit"));
    System.out.println(id + "---" + name + "---" + atk + "---" + hit + "---" + crit);
}
    //2---逐暮---100---1001---10000
    //3---风跃---9000---11---255
cursor.close();//关闭游标

2.查询一个:?为占位符,后面String数组对应站位符位置,占位符可多个。

Cursor cursor2 = mDb.rawQuery("SELECT * FROM sword WHERE id = ?", new String[]{"2"});
while (cursor2.moveToNext()) {
    String id = cursor2.getString(cursor2.getColumnIndex("id"));
    String name = cursor2.getString(cursor2.getColumnIndex("name"));
    String atk = cursor2.getString(cursor2.getColumnIndex("atk"));
    String hit = cursor2.getString(cursor2.getColumnIndex("hit"));
    String crit = cursor2.getString(cursor2.getColumnIndex("crit"));
    System.out.println(id + "---" + name + "---" + atk + "---" + hit + "---" + crit);
}
//2---逐暮---100---1001---10000
cursor2.close();//关闭游标

四、其他知识点

1.关于主键自增长和字段默认值

/**
 * 建表语句
 */
public static final String CREATE_TABLE = "CREATE TABLE sword (\n" +
        "_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n" +
        "name VARCHAR(32) NOT NULL,\n" +
        "atk SMALLINT UNSIGNED DEFAULT 1000,\n" +
        "hit SMALLINT UNSIGNED DEFAULT 20,\n" +
        "crit SMALLINT UNSIGNED DEFAULT 10\n" +
        ");";

2.可以将常用操作封装到一个dao类中

/**
 * 作者:张风捷特烈<br/>
 * 时间:2018/8/26 0026:17:50<br/>
 * 邮箱:1981462002@qq.com<br/>
 * 说明:数据库操作类
 */
public class SwordDao {
    private static SwordDao sSwordDao;
    private SQLiteDatabase db;

    /**
     * 私有化构造函数
     */
    private SwordDao() {
    }

    /**
     * 单例模式获取SwordDao
     *
     * @return SwordDao
     */
    public static SwordDao get() {
        if (sSwordDao == null) {
            synchronized (SwordDao.class) {
                if (sSwordDao == null) {
                    sSwordDao = new SwordDao();
                }
            }
        }
        return sSwordDao;
    }

    public SwordDao attach(SQLiteDatabase db) {
        this.db = db;
        return this;
    }

    /**
     * 查询所有
     * @return
     */
    public List<Sword> findAll() {
        Cursor cursor = db.rawQuery("SELECT * FROM sword", null);
        List<Sword> swords = new ArrayList<>();
        while (cursor.moveToNext()) {
            String tempId = cursor.getString(cursor.getColumnIndex("_id"));
            String name = cursor.getString(cursor.getColumnIndex("name"));
            String tempAtk = cursor.getString(cursor.getColumnIndex("atk"));
            String tempHit = cursor.getString(cursor.getColumnIndex("hit"));
            String tempCrit = cursor.getString(cursor.getColumnIndex("crit"));

            int id = tempId == null ? -1 : Integer.parseInt(tempId);
            int atk = tempAtk == null ? -1 : Integer.parseInt(tempAtk);
            int hit = tempHit == null ? -1 : Integer.parseInt(tempHit);
            int crit = tempCrit == null ? -1 : Integer.parseInt(tempCrit);

            Sword sword = new Sword(name, atk, hit, crit);
            sword.setId(id);
            swords.add(sword);
        }
        cursor.close();//关闭游标
        return swords;
    }
    
    /**
     * 插入
     * @param sword
     */
    public void insert(Sword sword) {
        db.execSQL("INSERT INTO sword(name,atk,hit,crit) VALUES(?,?,?,?)",
                new String[]{
                        sword.getName(), sword.getAtk() + "", sword.getHit() + "", sword.getCrit() + ""});
    }

    /**
     * 插入一个剑名称,其他默认
     *
     * @param name 名称
     */
    public void insert(String name) {
        db.execSQL("INSERT INTO sword(name) VALUES(?)",
                new String[]{name});
    }
}

后记:捷文规范

1.本文成长记录及勘误表

项目源码 日期 备注
V0.1--无 2018-8-26 1-SI--安卓SQLite基础使用指南
V0.2--无 2018-10-23 增加其他知识点

2.更多关于我

笔名 QQ 微信 爱好
张风捷特烈 1981462002 zdl1994328 语言
我的github 我的简书 我的CSDN 个人网站

3.声明

1----本文由张风捷特烈原创,转载请注明

2----欢迎广大编程爱好者共同交流

3----个人能力有限,如有不正之处欢迎大家批评指证,必定虚心改正

4----看到这里,我在此感谢你的喜欢与支持


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

缺失的终结

缺失的终结

【美】克尔•哈里斯 / 艾博 / 中国人民大学出版社 / 2017-6-15 / 39.00元

《缺失的终结》是一本反思互联网时代对普通人日常生活影响的书。作者认为,我们都曾渴望有一段远离现实生活烦扰的“瓦尔登湖”时光,悠闲地沉入自己的内心世界,从飞速变化的漩涡中暂时“缺失”。然而,互联网生活让我们每时每刻被互联网化,手环监测着我们的心跳和睡眠,微信、脸书、推特让我们人在床上就与世界链接起来,跑步了吗?走路了吗?英语单词背了吗?早餐的卡路里是否超标?坐在办公室,无数亟待处理的信息狂风暴雨般地......一起来看看 《缺失的终结》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

html转js在线工具
html转js在线工具

html转js在线工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具