15.android SQLite資料庫實現增刪該查和android測試test框架
阿新 • • 發佈:2018-12-23
SQliteOpenHelper是一個抽象類,來管理資料庫的建立和版本的管理。這個輔助類繼承自SQLiteOpenHelper類,在該類的構造器中,呼叫Context中的方法建立並開啟一個指定名稱的資料庫物件。繼承和擴充套件SQLiteOpenHelper類主要做的工作就是重寫以下兩個方法。
onCreate(SQLiteDatabase db) : 當資料庫被首次建立時執行該方法,一般將建立表等初始化操作在該方法中執行。
onUpgrade(SQLiteDatabse dv, int oldVersion,int new Version):當開啟資料庫時傳入的版本號與當前的版本號不同時會呼叫該方法。
SQLiteOpenHelper 類的基本用法是:當需要建立或開啟一個數據庫並獲得資料庫物件時,首先根據指定的檔名建立一個輔助物件,然後呼叫該物件的getWritableDatabase 或 getReadableDatabase方法 獲得SQLiteDatabase 物件。
android可以不需要啟動整個系統,單獨執行某一個方法,在方法的右邊,如test()選擇右鍵test-android run junit test執行就可以單獨測試某一個方法了(虛擬機器需要開啟)。
首先需要在清單檔案Manifist中配置一下才行,配置的內容和方法如下
配置AndroidManifist.xml檔案 <instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="com.ldw.sqlite" ></instrumentation> <uses-library android:name="android.test.runner"></uses-library>
清單檔案
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.ldw.sqlite" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="com.ldw.sqlite" ></instrumentation> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <uses-library android:name="android.test.runner"></uses-library>" <activity android:name="com.ldw.sqlite.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
MainActivity.java這裡什麼都沒有做,都是再test case中執行的
package com.ldw.sqlite;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
SQLiteOpenHelper.java資料庫的介面
package com.ldw.sqlite;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class MyOpenHelper extends SQLiteOpenHelper {
public MyOpenHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
//資料庫建立時呼叫
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table person(_id integer primary key autoincrement, name char(10), salary char(20), phone integer(20))");
System.out.println("建立資料庫");
}
//資料庫升級時呼叫
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
System.out.println("資料庫升級了");
}
}
TestCase.java測試資料庫的增刪改查
package com.ldw.sqlite.test;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.test.AndroidTestCase;
import com.ldw.sqlite.MyOpenHelper;
public class TestCase extends AndroidTestCase{
private MyOpenHelper oh;
private SQLiteDatabase db;
public void test(){
//getContext()是獲取虛擬的上下文
oh = new MyOpenHelper(getContext(), "people.db", null, 1);
//獲取可寫可讀資料庫物件,如果資料庫存在,直接開啟,如果資料庫不存在,先建立
//資料庫再獲取科協的資料庫物件
db = oh.getWritableDatabase();
}
//測試框架初始化完畢後,在測試方法執行之前,此方法呼叫
@Override
protected void setUp() throws Exception{
super.setUp();
oh = new MyOpenHelper(getContext(), "people.db", null, 1);
db = oh.getWritableDatabase();
}
//測試方法執行完畢以後此方法呼叫
@Override
protected void tearDown() throws Exception{
super.tearDown();
db.close();
}
public void insert(){
db.execSQL("insert into person (name, salary, phone)values(?, ?, ?)",new Object[]{"fhgfhf", "14000", 1302549110});
db.execSQL("insert into person (name, salary, phone)values(?, ?, ?)",new Object[]{"ghfhfh", "14000", 1302549110});
db.execSQL("insert into person (name, salary, phone)values(?, ?, ?)",new Object[]{"74gfhfhhfhf9", "14000", 1302549110});
}
public void delete(){
db.execSQL("delete from person where name = ?",new Object[]{"aaaaa"});
}
public void update(){
db.execSQL("update person set phone = ? where name = ?", new Object[]{321312, "aaaaa"});
}
public void select(){
Cursor cursor = db.rawQuery("select name, salary from person ", null);
while(cursor.moveToNext()){
//通過列索引獲取到列的值
String name = cursor.getString(cursor.getColumnIndex("name"));
String salary = cursor.getString(1);
System.out.println("name=" + name + "salary" + salary);
}
}
///API方法實現增刪該查
public void insertApi(){
//把要插入的資料全部封裝到ContentValues物件
ContentValues values = new ContentValues();
values.put("name", "xxx");
values.put("phone", "234324");
values.put("salary",13423);
db.insert("person", null, values);
}
public void deleteApi(){
//返回刪除的行數
int i = db.delete("person", "name = ? and _id = ?", new String[]{"aaaaa" , "4"});
}
public void updateApi(){
ContentValues values = new ContentValues();
values.put("salary", 17000);
//返回修改的行數
int i = db.update("person", values, "name = ?", new String[]{"xxx"});
System.out.println("i"+i);
}
public void selectApi(){
Cursor cursor = db.query("person", null, null, null, null, null, null, null);
while(cursor.moveToNext()){
String name = cursor.getString(cursor.getColumnIndex("name"));
String phone = cursor.getString(cursor.getColumnIndex("phone"));
String salary = cursor.getString(cursor.getColumnIndex("salary"));
System.out.println("name = " + name + "phone = " + phone + "salary = " + salary);
}
}
public void transation(){
try{
//開啟事務
db.beginTransaction();
ContentValues values = new ContentValues();
values.put("salary", 40000);
db.update("person", values, "name = ?", new String[]{"luodewu"});
//上下都使用一個values防止資料干擾
values.clear();
values.put("salary", 20000);
db.update("person", values, "name = ?", new String[]{"luodewuluodewu"});
//設定事物執行成功
db.setTransactionSuccessful();
}
finally{
//關閉事物,同時提交,如果已經設定事務執行成功,sql語句就生效了,反之語句回滾
db.endTransaction();
}
}
}
activity_main.xml佈局檔案。因為是測試case,這個檔案沒有什麼用
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>