SQLite基本知識點總結
- 前言
- 1. 定義
- 2. 建立資料庫
- 3. 資料庫更新
- 4. 資料庫的CRUD
-
- 4.1 Create
- 4.2 Update
- 4.3 Delete
- 4.4 Query
- 參考材料
前言
- 開始之前,我會new一個project,并add一個empty activity,然後不做其他任何操作。
- 接下來邊寫文章邊敲代碼。
- 最終項目在這,非常簡單的項目:https://github.com/wodongx123/SQLiteDemo/
1. 定義
SQlite是Android系統内置的一個輕量級的關系型資料庫,運作速度快,占用記憶體小,不僅支援原生的SQL語句還支援ACID事務1,使用甚至不需要賬号密碼。
2. 建立資料庫
- SQlite的管理需要使用Android提供的SQLiteOpenHelper類,不過這是一個抽象類想要使用它要自己建立一個類來繼承它,然後重寫其中的方法來消除錯誤。
public class MyDataBaseHelper extends SQLiteOpenHelper { public myDataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { } }
看上去代碼很多,其實都是為了消除錯誤添加的,添加完之後自然而然就長這樣了。
其中構造函數有兩個方法,我們用參數少的那個,有關構造函數的參數看表。
為了友善,到時候資料庫名字就叫BookStore.db。參數 描述 Context 建立資料所需要的環境,一般就傳所在的activity name 這個就是資料庫的名字了,建立完的資料庫的名字就是傳入的參數 factory 自定義的遊标,沒有明确計劃或不知道的話就傳null version 資料庫的版本号,更新版本時用 -
這樣一來資料庫就算是建立完了,在建立完資料庫之後接下來要做的就是建表,表名叫book。
建表的SQL語句:
對于SQLite而言,執行sql語句不用太過複雜,直接使用SQLiteDatabase的execSQL()就好,把它寫在onCreate()裡面。create table book( id integer primary key autoincrement, name text, author text, price integer )
public class MyDataBaseHelper extends SQLiteOpenHelper { //将建表的SQL語句寫成String的常量 public static final String createBookTable = "create table book(\n" + "id integer primary key autoincrement,\n" + "name text,\n" + "author text,\n" + "price integer\n" + ")"; …………………… @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { //執行SQL語句 sqLiteDatabase.execSQL(createBookTable); } …………………… }
- 最後在MainActivity中配置,資料庫和表就會自然建立成功。
但是建立完資料庫後,要怎麼樣才能看到内容呢,看不到的話,是不是真的創完資料庫和表也很難說吧。這個時候就要使用工具SQLiteStudio了。public class MainActivity extends AppCompatActivity { private MyDataBaseHelper myDataBaseHelper; SQLiteDatabase writableDatabase; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myDataBaseHelper = new MyDataBaseHelper(this, "BookStore.db", null, 1); //擷取一個可寫的資料庫,當管理類發現沒有這個資料庫的時候,就會建立一個,順便就執行了oncreate的建表 writableDatabase = myDataBaseHelper.getWritableDatabase(); } }
-
下載下傳SQLiteStudio,由于是Window和Mac和Linux都能用,不用擔心平台問題,連結如果不能用了請自行百度。
https://sqlitestudio.pl/index.rvt?act=download
- 在你的Android Studio的右下角有個Device Explorer,點開後找到對應的路徑:/data/data/項目名/database/BookStore.db
- 項目名不知道可以打開AndroidManifest.xml檢視。
- 把這個BookStore.db右鍵Save as到一個你知道路徑的位置(比如說桌面),然後用SQLiteStudio打開它。
- 可以看到資料庫确實有建立,而表也确實存在,就是内部還沒有資料。
-
3. 資料庫更新
-
在MyDatabaseHelper類中,還有一個onUpgrade方法是空着沒寫的,這個方法就是用于更新資料庫用,現在的目标是要建立一個新的表People來使用。
可能你會有疑問,為啥兩個表不一次性一起創完而是要這樣分開建立。實際上在工作中經常會因為更新維護而追加功能,這個people表就是模拟這種追加功能的情況.
- 建立People表的SQL:
然後寫在onUpgrade()中create table People( id integer primary key autoincrement, name text, age integer )
public class MyDataBaseHelper extends SQLiteOpenHelper { //将建表的SQL語句寫成String的常量 public static final String createPeopleTable = "create table People(\n" + "id integer primary key autoincrement,\n" + "name text,\n" + "age integer\n" + ")"; …………………… @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { sqLiteDatabase.execSQL(createPeopleTable); } …………………… }
-
重新運作項目,然後把BookStore.db拉出來檢視,發現其中并沒有更新People表。這是因為onUpgrade是隻有在資料庫版本更新的時候才會調用的方法。這個版本,其實就是我們在調用構造函數時所傳入的參數。
回到MainActivity,将構造函數的那個版本号1改成2,再次運作項目。
- 再次把BookStore.db儲存到本地用SQLiteStudio打開,确認新的表确實有添加。
4. 資料庫的CRUD
所謂CRUD,也就是Create,Retrieve,Update,Delete,也就是我們常說的增删改查。在建立完表之後,接下來要做的就是對表内的資料進行增删改查。
4.1 Create
向表内添加新的資料,需要從使用SQLiteDatabase的insert方法。由于在MyDatabaseHelper類不好操作,一般是在外部進行操作,這裡就用MainActivity對資料庫操作。
public class MainActivity extends AppCompatActivity {
private MyDataBaseHelper myDataBaseHelper;
SQLiteDatabase writableDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
……………………
insert();
}
public void insert(){
//擷取一個可寫的資料庫,這樣才能寫入資料
writableDatabase = myDataBaseHelper.getWritableDatabase();
//對資料庫進行增改需要使用ContentValues,它是一個存儲類,可以存儲大部分基本類型的資料
ContentValues values = new ContentValues();
values.put("name", "hello world");
values.put("author", "aaa");
values.put("price", 100);
//添加資料,
writableDatabase.insert("Book", null, values);
//清空内容,然後寫入第二段資料
values.clear();
values.put("name", "hello android");
values.put("price", 200);
//再次添加資料,
writableDatabase.insert("Book", null, values);
}
}
對應的SQL:
insert into Book (name, author, price) values(‘hello world’, ‘aaa’, 100)
insert into Book (name, price) values(‘hello android’, 200)
結果用SQLiteStudio查詢。
4.2 Update
添加完資料之後,接下來就是要更新資料了,這個需要使用到update方法。
public class MainActivity extends AppCompatActivity {
private MyDataBaseHelper myDataBaseHelper;
SQLiteDatabase writableDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
……………………
//insert();
update();
}
……………………
public void update(){
//擷取一個可寫的資料庫,這樣才能更新資料
writableDatabase = myDataBaseHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("author", "bbb");
values.put("price", 150);
writableDatabase.update("Book", values, "name = ?", new String[]{"hello android"});
}
}
有關update方法的參數,第一個第二個參數相當于insert方法的第一個第三個參數,代表表名和資料段,第三個參數則是SQL語句的where部分,而第四個參數則是對第三個參數中的’?‘部分給出具體值,一個資料對應一個問号,而這個’?'就是占位符。不太好了解,但是看完SQL的寫法你就懂了。
SQL:
update Book set author = ‘bbb’, price = 150 where name = ‘hello android’
4.3 Delete
不用多描述了,看看怎麼寫的就好,調用Delete方法。
public class MainActivity extends AppCompatActivity {
private MyDataBaseHelper myDataBaseHelper;
SQLiteDatabase writableDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
……………………
// insert();
// update();
delete();
}
……………………
public void delete(){
writableDatabase = myDataBaseHelper.getWritableDatabase();
writableDatabase.delete("Book", "author = ?", new String[]{"bbb"});
}
}
SQL:
delete from Book where author = ‘bbb’
4.4 Query
對于資料庫最重要的内容而言,就是查詢。查詢功能非常重要,是以就算是最直接的query方法也帶有非常多參數,在此我先對參數進行描述說明。
參數 | 對應SQL部分 | 備注 |
---|---|---|
table | from table_1 | 查詢某個應用中的某個表 |
column | select column1, column2 | 查詢指定的列名,如果為空就是選擇所有列(相當于*) |
selection | where column = value | 限制條件,如果為空就是沒有限制條件 |
selectionArgs | - | 為where中的占位符提供具體的值,為空就是無具體值,為new String[]{}形式 |
groupBy | group by column | 指定需要group by的列,可為空 |
having | having column = value | 對group by後的列進一步限制,可為空 |
orderBy | order by column1 | 指定查詢結果的排列方式,可為空 |
這裡為了友善,大部分參數到時候就都為空了。
public class MainActivity extends AppCompatActivity {
private MyDataBaseHelper myDataBaseHelper;
SQLiteDatabase writableDatabase;
SQLiteDatabase readableDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
……………………
//為了讓結果資料多一點,就再插入兩條資料
insert();
// update();
// delete();
query();
}
……………………
public void query(){
//由于不用對資料做改動,是以隻要擷取隻讀的資料庫即可
readableDatabase = myDataBaseHelper.getReadableDatabase();
//查詢語句,要注意傳回的是一個Cursor對象
Cursor cursor = readableDatabase.query("Book", null, null, null, null, null, null);
//如果查詢的資料為空就傳回
if (!cursor.moveToFirst())
return;
//當遊标沒到末尾時就一直周遊内部的資料
do{
String name = cursor.getString(cursor.getColumnIndex("name"));
int price = cursor.getInt(cursor.getColumnIndex("price"));
//為了友善,獲得的資料就用log打出
Log.i("MainActivity", "query: " + name + " " + price);
}while(cursor.moveToNext());
//用完之後要記得關掉
cursor.close();
}
}
SQL:
select * from Book
參考材料
第一行代碼——Android(第2版)
p211 - p229
-
有關ACID這個看百科就好了:
https://baike.baidu.com/item/ACID/10738 ↩︎