數(shù)據(jù)庫(kù)是Android存儲(chǔ)方案的核心,在Andorid中SQLite非常輕量,而且執(zhí)行sql語(yǔ)句甚至比MySQL還要快。
SQLiteDatabase 是 Android 中操作數(shù)據(jù)庫(kù)的核心類之一,使用SQLiteDatabase可以打開(kāi)數(shù)據(jù)庫(kù),也可以對(duì)數(shù)據(jù)庫(kù)進(jìn)行操作,然而,為了數(shù)據(jù)庫(kù)升級(jí)以及使用更加方便,我們常用SQLiteOpenHelper的子類來(lái)完成創(chuàng)建,打開(kāi)數(shù)據(jù)庫(kù)的操作。
SQLiteOpenHelper是一個(gè)抽象類,在該類中有下面兩個(gè)必須實(shí)現(xiàn)的方法:
public void onCreate(SQLiteDatabase db);// 該函數(shù)在數(shù)據(jù)庫(kù)第一次被建立時(shí)調(diào)用public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion);// 數(shù)據(jù)庫(kù)更新升級(jí)操作
我們新建一個(gè)類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ù)庫(kù)默認(rèn)版本 private static final int VERSON = 1; // 自定義數(shù)據(jù)庫(kù)名,可以隨便取名字 private static final String DBNAME = "mydb"; // 繼承SQLiteOpenHelper類的類必須有自己的構(gòu)造函數(shù) // 該構(gòu)造函數(shù)4個(gè)參數(shù),直接調(diào)用父類的構(gòu)造函數(shù)。其中第一個(gè)參數(shù)為該類本身;第二個(gè)參數(shù)為數(shù)據(jù)庫(kù)的名字; public DBHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); } // 該構(gòu)造函數(shù)有3個(gè)參數(shù),因?yàn)樗焉厦婧瘮?shù)的第3個(gè)參數(shù)固定為null了 public DBHelper(Context context, String name, int verson) { this(context, name, null, verson); } // 該構(gòu)造函數(shù)只有2個(gè)參數(shù),在上面函數(shù) 的基礎(chǔ)上將版本號(hào)固定了 public DBHelper(Context context, String name) { this(context, name, VERSON); } // 該構(gòu)造函數(shù)只有1個(gè)參數(shù),固定默認(rèn)數(shù)據(jù)庫(kù),在這里我們實(shí)現(xiàn)增刪改查為了方便,就用它了 public DBHelper(Context context) { this(context, DBNAME, null, VERSON); } // 該函數(shù)在數(shù)據(jù)庫(kù)第一次被建立時(shí)調(diào)用 public void onCreate(SQLiteDatabase db) { System.out.println("create a sqlite database"); //建表語(yǔ)句(注意:因?yàn)樵诮壎〝?shù)據(jù)時(shí),Cursor對(duì)象返回的記錄集中必須包含一個(gè)"_id"字段,否則無(wú)法完成數(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ù)庫(kù)更新操作 public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) { System.out.println("update a sqlite database"); } //自定義query方法,用以執(zhí)行查詢語(yǔ)句,返回Cursor對(duì)象 public Cursor query(String sql,String[] args){ //調(diào)用 getReadableDatabase方法時(shí),如果數(shù)據(jù)庫(kù)文件不存在,會(huì)調(diào)用 onCreate方法 SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(sql, args); return cursor; }}
這樣,我們的DBHelper 類寫好了,我們來(lái)實(shí)現(xiàn)一個(gè)查詢操作。
第一步,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>
第二步,新建一個(gè)xml布局文件,用來(lái)作為列表項(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個(gè)參數(shù)的構(gòu)造函數(shù),實(shí)例化dbHelper DBHelper dbHelper = new DBHelper(this); //新建Cursor對(duì)象來(lái)保存query查詢方法返回的結(jié)果,查詢test表中所有記錄 Cursor cursor = dbHelper.query("select * from test", null); //創(chuàng)建SimpleCursorAdapter對(duì)象,5個(gè)參數(shù), //第一個(gè)是context,就寫當(dāng)前this就行 //第二個(gè)是布局文件,我這里是自定義的布局文件user_list_cell.xml //第三個(gè)就是Cursor對(duì)象 //第四個(gè)對(duì)應(yīng)就是,cursor查詢后,需要顯示出來(lái)的字段名,比如我要顯示姓名name和年齡age //第五個(gè)就是對(duì)應(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ù)庫(kù)應(yīng)了解,對(duì)數(shù)據(jù)庫(kù)的增刪改查都有兩種方法,一種是前面的使用 rawQuery方法直接執(zhí)行SQL語(yǔ)句,另一種就是使用SQLiteDatabase類的相應(yīng)方法來(lái)操作,下面舉一個(gè)第二種的例子,比如我們要插入數(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個(gè)參數(shù)的構(gòu)造函數(shù),實(shí)例化dbHelper //DBHelper dbHelper = new DBHelper(this); ////新建Cursor對(duì)象來(lái)保存query查詢方法返回的結(jié)果,查詢test表中所有記錄 //Cursor cursor = dbHelper.query("select * from test", null); ////創(chuàng)建SimpleCursorAdapter對(duì)象,5個(gè)參數(shù), ////第一個(gè)是context,就寫當(dāng)前this就行 ////第二個(gè)是布局文件,我這里是自定義的布局文件user_list_cell.xml ////第三個(gè)就是Cursor對(duì)象 ////第四個(gè)對(duì)應(yīng)就是,cursor查詢后,需要顯示出來(lái)的字段名,比如我要顯示姓名name和年齡age ////第五個(gè)就是對(duì)應(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í)行插入成功以后,再將插入語(yǔ)句注釋,將查詢語(yǔ)句去掉注釋,重新啟動(dòng),會(huì)發(fā)現(xiàn)最后一多了一個(gè)item,添加成功。
另外查詢記錄獲得的Cursor對(duì)象,需要使用movetoFirst,moveToNext,movToPosition(position)等方法將指針移動(dòng)相應(yīng)的位置,來(lái)進(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對(duì)象的查詢操作 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不為空 這個(gè)很重要 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個(gè)參數(shù)的構(gòu)造函數(shù),實(shí)例化dbHelper //DBHelper dbHelper = new DBHelper(this); ////新建Cursor對(duì)象來(lái)保存query查詢方法返回的結(jié)果,查詢test表中所有記錄 //Cursor cursor = dbHelper.query("select * from test", null); ////創(chuàng)建SimpleCursorAdapter對(duì)象,5個(gè)參數(shù), ////第一個(gè)是context,就寫當(dāng)前this就行 ////第二個(gè)是布局文件,我這里是自定義的布局文件user_list_cell.xml ////第三個(gè)就是Cursor對(duì)象 ////第四個(gè)對(duì)應(yīng)就是,cursor查詢后,需要顯示出來(lái)的字段名,比如我要顯示姓名name和年齡age ////第五個(gè)就是對(duì)應(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中。是不是很有意思呢?
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選