詳解Android輕量型數(shù)據(jù)庫SQLite
數(shù)據(jù)庫是Android存儲方案的核心,在Andorid中SQLite非常輕量,而且執(zhí)行sql語句甚至比MySQL還要快。
SQLiteDatabase 是 Android 中操作數(shù)據(jù)庫的核心類之一,使用SQLiteDatabase可以打開數(shù)據(jù)庫,也可以對數(shù)據(jù)庫進(jìn)行操作,然而,為了數(shù)據(jù)庫升級以及使用更加方便,我們常用SQLiteOpenHelper的子類來完成創(chuàng)建,打開數(shù)據(jù)庫的操作。
SQLiteOpenHelper是一個抽象類,在該類中有下面兩個必須實(shí)現(xiàn)的方法:
public void onCreate(SQLiteDatabase db);// 該函數(shù)在數(shù)據(jù)庫第一次被建立時調(diào)用 public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion);// 數(shù)據(jù)庫更新升級操作
我們新建一個類DBHelper extends SQLiteOpenHelper
import java.util.Random;
import android.R.bool;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
// 設(shè)置數(shù)據(jù)庫默認(rèn)版本
private static final int VERSON = 1;
// 自定義數(shù)據(jù)庫名,可以隨便取名字
private static final String DBNAME = "mydb";
// 繼承SQLiteOpenHelper類的類必須有自己的構(gòu)造函數(shù)
// 該構(gòu)造函數(shù)4個參數(shù),直接調(diào)用父類的構(gòu)造函數(shù)。其中第一個參數(shù)為該類本身;第二個參數(shù)為數(shù)據(jù)庫的名字;
public DBHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
}
// 該構(gòu)造函數(shù)有3個參數(shù),因?yàn)樗焉厦婧瘮?shù)的第3個參數(shù)固定為null了
public DBHelper(Context context, String name, int verson) {
this(context, name, null, verson);
}
// 該構(gòu)造函數(shù)只有2個參數(shù),在上面函數(shù) 的基礎(chǔ)上將版本號固定了
public DBHelper(Context context, String name) {
this(context, name, VERSON);
}
// 該構(gòu)造函數(shù)只有1個參數(shù),固定默認(rèn)數(shù)據(jù)庫,在這里我們實(shí)現(xiàn)增刪改查為了方便,就用它了
public DBHelper(Context context) {
this(context, DBNAME, null, VERSON);
}
// 該函數(shù)在數(shù)據(jù)庫第一次被建立時調(diào)用
public void onCreate(SQLiteDatabase db) {
System.out.println("create a sqlite database");
//建表語句(注意:因?yàn)樵诮壎〝?shù)據(jù)時,Cursor對象返回的記錄集中必須包含一個"_id"字段,否則無法完成數(shù)據(jù)綁定
String sql = "CREATE TABLE [test]("+
"[_id] AUTOINC,"+
"[name] varchar(20),"+
"[age] varchar(20),"+
"PRIMARY KEY ([_id]))";
db.execSQL(sql);
//向test表中插入10條數(shù)據(jù)
for (int i = 1; i <= 10; i++) {
String name = "Jepson";
name+=i;
String age = "age";
age+=i;
db.execSQL("insert into test(name,age) values(?,?)",new Object[]{name,age});
}
}
// 數(shù)據(jù)庫更新操作
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
System.out.println("update a sqlite database");
}
//自定義query方法,用以執(zhí)行查詢語句,返回Cursor對象
public Cursor query(String sql,String[] args){
//調(diào)用 getReadableDatabase方法時,如果數(shù)據(jù)庫文件不存在,會調(diào)用 onCreate方法
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(sql, args);
return cursor;
}
}
這樣,我們的DBHelper 類寫好了,我們來實(shí)現(xiàn)一個查詢操作。
第一步,activity_main.xml添加 listview 展示控件
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#FFFFFF" android:orientation="vertical" tools:context=".MainActivity" > <ListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" android:divider="#6b6f74" android:dividerHeight="1px" > </ListView> </LinearLayout>
第二步,新建一個xml布局文件,用來作為列表項(xiàng)使用的布局資源
user_list_cell.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="#FFFFFF"> <!-- 大字體TextView,用以展示 name姓名 --> <TextView android:id="@+id/tvName" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Large" android:textColor="#000000" android:textSize="20dp" /> <!-- 小字體TextView,用以展示 age年齡 --> <TextView android:id="@+id/tvAge" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Small" android:textColor="#000000" android:textSize="14dp" /> </LinearLayout>
第三步,主Activity
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.database.Cursor;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends ListActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
public void initView(){
//調(diào)用只有1個參數(shù)的構(gòu)造函數(shù),實(shí)例化dbHelper
DBHelper dbHelper = new DBHelper(this);
//新建Cursor對象來保存query查詢方法返回的結(jié)果,查詢test表中所有記錄
Cursor cursor = dbHelper.query("select * from test", null);
//創(chuàng)建SimpleCursorAdapter對象,5個參數(shù),
//第一個是context,就寫當(dāng)前this就行
//第二個是布局文件,我這里是自定義的布局文件user_list_cell.xml
//第三個就是Cursor對象
//第四個對應(yīng)就是,cursor查詢后,需要顯示出來的字段名,比如我要顯示姓名name和年齡age
//第五個就是對應(yīng)列表項(xiàng)布局中的控件ID了
SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(this,
R.layout.user_list_cell, cursor,
new String[] { "name", "age" }, new int[] { R.id.tvName,
R.id.tvAge });
setListAdapter(simpleCursorAdapter);
Toast.makeText(this, "查詢成功", Toast.LENGTH_SHORT).show();
}
}
執(zhí)行一下看看,我們是不是查詢成功了?
操作SQLite數(shù)據(jù)庫應(yīng)了解,對數(shù)據(jù)庫的增刪改查都有兩種方法,一種是前面的使用 rawQuery方法直接執(zhí)行SQL語句,另一種就是使用SQLiteDatabase類的相應(yīng)方法來操作,下面舉一個第二種的例子,比如我們要插入數(shù)據(jù) name=11 age=22
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.database.Cursor;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends ListActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
public void initView(){
//執(zhí)行添加操作
DBHelper dbHelper = new DBHelper(this);
//獲得寫入權(quán)限getWritableDatabase
SQLiteDatabase db = dbHelper.getWritableDatabase();
//新建contentvalues保存insert數(shù)據(jù)
ContentValues cv = new ContentValues();
cv.put("name", "11");
cv.put("age", "22");
db.insert("test", null, cv);
Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();
////查詢操作
////調(diào)用只有1個參數(shù)的構(gòu)造函數(shù),實(shí)例化dbHelper
//DBHelper dbHelper = new DBHelper(this);
////新建Cursor對象來保存query查詢方法返回的結(jié)果,查詢test表中所有記錄
//Cursor cursor = dbHelper.query("select * from test", null);
////創(chuàng)建SimpleCursorAdapter對象,5個參數(shù),
////第一個是context,就寫當(dāng)前this就行
////第二個是布局文件,我這里是自定義的布局文件user_list_cell.xml
////第三個就是Cursor對象
////第四個對應(yīng)就是,cursor查詢后,需要顯示出來的字段名,比如我要顯示姓名name和年齡age
////第五個就是對應(yīng)列表項(xiàng)布局中的控件ID了
//SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(this,
// R.layout.user_list_cell, cursor,
// new String[] { "name", "age" }, new int[] { R.id.tvName,
// R.id.tvAge });
//setListAdapter(simpleCursorAdapter);
//Toast.makeText(this, "查詢成功", Toast.LENGTH_SHORT).show();
}
}
執(zhí)行插入成功以后,再將插入語句注釋,將查詢語句去掉注釋,重新啟動,會發(fā)現(xiàn)最后一多了一個item,添加成功。
另外查詢記錄獲得的Cursor對象,需要使用movetoFirst,moveToNext,movToPosition(position)等方法將指針移動相應(yīng)的位置,來進(jìn)行查詢結(jié)果的讀取。
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.database.Cursor;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends ListActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
public void initView(){
//解析Cursor對象的查詢操作
DBHelper dbHelper = new DBHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = db.query("test", null, null, null, null, null, null,
null);
//定義結(jié)果字符串
String result = "";
// 判斷cursor不為空 這個很重要
if (cursor != null) {
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex("name"));// 獲取name列的值
String age = cursor.getString(cursor.getColumnIndex("age"));// 獲取age列的值
result += "姓名:" + name + ",年齡:" + age + "\n";
}
}
cursor.close();
db.close();
System.out.println(result);
Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
// //執(zhí)行添加操作
// DBHelper dbHelper = new DBHelper(this);
// //獲得寫入權(quán)限getWritableDatabase
// SQLiteDatabase db = dbHelper.getWritableDatabase();
// //新建contentvalues保存insert數(shù)據(jù)
// ContentValues cv = new ContentValues();
// cv.put("name", "11");
// cv.put("age", "22");
// db.insert("test", null, cv);
// Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();
////查詢操作
////調(diào)用只有1個參數(shù)的構(gòu)造函數(shù),實(shí)例化dbHelper
//DBHelper dbHelper = new DBHelper(this);
////新建Cursor對象來保存query查詢方法返回的結(jié)果,查詢test表中所有記錄
//Cursor cursor = dbHelper.query("select * from test", null);
////創(chuàng)建SimpleCursorAdapter對象,5個參數(shù),
////第一個是context,就寫當(dāng)前this就行
////第二個是布局文件,我這里是自定義的布局文件user_list_cell.xml
////第三個就是Cursor對象
////第四個對應(yīng)就是,cursor查詢后,需要顯示出來的字段名,比如我要顯示姓名name和年齡age
////第五個就是對應(yīng)列表項(xiàng)布局中的控件ID了
//SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(this,
// R.layout.user_list_cell, cursor,
// new String[] { "name", "age" }, new int[] { R.id.tvName,
// R.id.tvAge });
//setListAdapter(simpleCursorAdapter);
//Toast.makeText(this, "查詢成功", Toast.LENGTH_SHORT).show();
}
}
執(zhí)行以后,可以發(fā)現(xiàn),name和age全都獲取到了,并顯示在了Toast和system.out中。是不是很有意思呢?
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Android SQLite數(shù)據(jù)庫增刪改查操作的使用詳解
- Android開發(fā)之SQLite的使用方法
- Android使用SQLite數(shù)據(jù)庫的簡單實(shí)例
- android創(chuàng)建數(shù)據(jù)庫(SQLite)保存圖片示例
- 深入Android SQLite 事務(wù)處理詳解
- Android--SQLite(增,刪,改,查)操作實(shí)例代碼
- Android中的SQL查詢語句LIKE綁定參數(shù)問題解決辦法(sqlite數(shù)據(jù)庫)
- android中sqlite的按條件查找的小例子
- android開發(fā)教程之listview顯示sqlite數(shù)據(jù)
- Android 用SQLite實(shí)現(xiàn)事務(wù)的方法
相關(guān)文章
Android使用WebSocket實(shí)現(xiàn)多人游戲
WebSocket 是 HTML5 一種新的協(xié)議。實(shí)現(xiàn)了瀏覽器與服務(wù)器全雙工通信,下面通過本文給大家分享Android使用WebSocket實(shí)現(xiàn)多人游戲,需要的朋友參考下吧2017-11-11
Android中使用Bitmap類將矩形圖片轉(zhuǎn)為圓形的方法
這篇文章主要介紹了Android中使用Bitmap類將矩形圖片轉(zhuǎn)為圓形的方法,同時文中也介紹了如何利用矩形直接來畫圓角,需要的朋友可以參考下2016-03-03
Android開發(fā)實(shí)現(xiàn)撥打電話與發(fā)送信息的方法分析
這篇文章主要介紹了Android開發(fā)實(shí)現(xiàn)撥打電話與發(fā)送信息的方法,結(jié)合實(shí)例形式分析了Android撥打電話及發(fā)送信息相關(guān)布局、功能實(shí)現(xiàn)及權(quán)限控制操作技巧,需要的朋友可以參考下2017-12-12
Android實(shí)現(xiàn)類似iOS分欄控制器
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)類似iOS分欄控制器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03
Android利用動畫實(shí)現(xiàn)背景逐漸變暗
這篇文章主要為大家詳細(xì)介紹了Android利用動畫實(shí)現(xiàn)背景逐漸變暗的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-12-12

