安卓SQLite基礎使用指南

零、前言

[1]熟悉MySQL的學這個就像會西瓜的人去學吃哈密瓜同樣簡單。
[2]若是對MySQL不太熟悉的童鞋,能夠看一下個人這篇 :SpringBoot-14-MyBatis預熱篇,MySQL小結
[3]SQLite:安卓內置輕量級的關係型數據庫
[4]強烈建議語句什麼的提早寫好,在MySQL上測試一下,否則少個分號,多個逗號什麼的就呵呵了
[5]安卓有API支持數據庫操做,但感受不怎麼靈活,感興趣的能夠本身瞭解一下
坑點

[1]:SQLite 不支持 DEFAULT 和 NOT NULL 連用(雖然連在一塊兒也沒啥用)java

[3]:INSERT INTO 的 INTO 要加上 (MySQL養成的壞毛病,得該)git


1、建立數據庫

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()異常

建立數據庫.png

2、升級數據庫時刪除表

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();//獲取可寫數據庫對象

3、數據庫的經常使用操做(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);

插入數據.png


2.刪除數據
/**
     * 刪除數據
     */
    public static final String DELETE = "DELETE FROM sword WHERE id=1;";
mDb = new MySQLHelper(this).getWritableDatabase();
mDb.execSQL(SQLCon.DELETE);

刪除數據.png


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

修改數據.png


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();//關閉遊標

4、其餘知識點

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----看到這裏,我在此感謝你的喜歡與支持
相關文章
相關標籤/搜索