數據庫對於仍和一個數據量較大的程序來講都是非常重要。這是一個非常輕量級的數據庫,對於每個程序來講,都有一個私密的數據庫,別的程序看不到,必需要用內容提供器才能給別的app使用,所以說是十分安全的,SQLite沒有用戶。今天學習了用execSQL來進行SQlite的插入查詢。
SQLite的創建
SQLite的創建非常簡單,使用一個SQLiteDatebase類即可
SQLiteDatabase db = openOrCreateDatabase("temp.db", MODE_PRIVATE, null);
SQlite同樣不能直接獲取實例,需要用openOrCreateDatabase來獲得,在沒有創建數據庫時創建,在有數據庫時打開,比較萬能。第一個參數很明顯時數據庫名,最好以.db來結尾。第二個參數是創建方式,推薦使用MODE_PRIVATE,第三個參數暫時以null結尾。
使用SQL語句操作數據庫
SQL語句一般直接保存在String中當作參數,傳入database的execSQL方法的參數中,代碼如下:
db.execSQL("create table if not exists usertb (_id integer primary key autoincrement," +
"name text not null," +
"age integer not null," +
"sex text not null" +
")");
db.execSQL("insert into usertb(name,age,sex) values('張三',18,'男')");
db.execSQL("insert into usertb(name,age,sex) values('李四',20,'男')");
db.execSQL("insert into usertb(name,age,sex) values('王五',19,'男')");
使用Cursor來查詢數據庫
數據庫創建完成了,自然要輪到查詢工作了,使用
Cursor cursor=db.rawQuery("select * from usertb",null);
這裏的 select * from usertb
表示從表爲usertb中獲得所有行。rawQuery會返回一個Cursor對象,只是一個遊標,默認指向第一行數據的上方,查詢代碼:
if (cursor != null) {
while (cursor.moveToNext()) {//cursor默認從第一條之上開始查詢
Toast.makeText(MainActivity.this, "正在查詢"+cursor.getString(cursor.getColumnIndex("name")), Toast.LENGTH_SHORT).show();
}
cursor.close();
}
這句代碼cursor.getColumnIndex("name")
表示從行中要提取名爲name的值,最後最好使用cursor.close()
將cursor對象關閉,否則當查詢數據過多時,會發生內存報錯。
關閉數據庫
最後的一部當然也別忘了db.close();
來將數據庫關閉。