Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android開發(10)使用SQLiteDatabase操作SQLite數據庫實現增刪改查

Android開發(10)使用SQLiteDatabase操作SQLite數據庫實現增刪改查

編輯:關於Android編程

Android提供了一個名為SQLiteDatabase的類,該類封裝了一些操作數據庫的API,使用該類可以完成對數據進行添加(Create)、查詢(Retrieve)、更新(Update)和刪除(Delete)操作(這些操作簡稱為CRUD)。對SQLiteDatabase的學習,我們應該重點掌握execSQL()和rawQuery()方法。 execSQL()方法可以執行insert、delete、update和CREATE TABLE之類有更改行為的SQL語句; rawQuery()方法可以執行select語句。
execSQL()方法的使用例子:
SQLiteDatabase db = ....;
db.execSQL("insert into person(name, age) values('CSDN', 4)");
db.close();
執行上面SQL語句會往person表中添加進一條記錄,在實際應用中, 語句中的“傳智播客”這些參數值會由用戶輸入界面提供,如果把用戶輸入的內容原樣組拼到上面的insert語句, 當用戶輸入的內容含有單引號時,組拼出來的SQL語句就會存在語法錯誤。要解決這個問題需要對單引號進行轉義,也就是把單引號轉換成兩個單引號。有些時候用戶往往還會輸入像“ & ”這些特殊SQL符號,為保證組拼好的SQL語句語法正確,必須對SQL語句中的這些特殊SQL符號都進行轉義,顯然,對每條SQL語句都做這樣的處理工作是比較煩瑣的。 SQLiteDatabase類提供了一個重載後的execSQL(String sql, Object[] bindArgs)方法,使用這個方法可以解決前面提到的問題,因為這個方法支持使用占位符參數(?)。使用例子如下:
SQLiteDatabase db = ....;
db.execSQL("insert into person(name, age) values(?,?)", new Object[]{"CSDN", 4});
db.close();
execSQL(String sql, Object[] bindArgs)方法的第一個參數為SQL語句,第二個參數為SQL語句中占位符參數的值,參數值在數組中的順序要和占位符的位置對應

除了前面給大家介紹的execSQL()和rawQuery()方法, SQLiteDatabase還專門提供了對應於添加、刪除、更新、查詢的操作方法: insert()、delete()、update()和query() 。這些方法實際上是給那些不太了解SQL語法的菜鳥使用的,對於熟悉SQL語法的程序員而言,直接使用execSQL()和rawQuery()方法執行SQL語句就能完成數據的添加、刪除、更新、查詢操作。
Insert()方法用於添加數據,各個字段的數據使用ContentValues進行存放。 ContentValues類似於MAP,相對於MAP,它提供了存取數據對應的put(String key, Xxx value)和getAsXxx(String key)方法, key為字段名稱,value為字段值,Xxx指的是各種常用的數據類型,如:String、Integer等。
SQLiteDatabase db = databaseHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", "csdn");
values.put("age", 4);
long rowid = db.insert(“person”, null, values);//返回新添記錄的行號,與主鍵id無關
不管第三個參數是否包含數據,執行Insert()方法必然會添加一條記錄,如果第三個參數為空,會添加一條除主鍵之外其他字段值為Null的記錄。Insert()方法內部實際上通過構造insert語句完成數據的添加,Insert()方法的第二個參數用於指定空值字段的名稱,相信大家對此參數會感到疑惑,此參數的作用是干嘛的?是這樣的:如果第三個參數values 為Null或者元素個數為0, Insert()方法必然要添加一條除了主鍵之外其它字段為Null值的記錄,為了滿足這條insert語句的語法, insert語句必須給定一個字段名,如:insert into person(name) values(NULL),倘若不給定字段名 , insert語句就成了這樣: insert into person() values(),顯然這不滿足標准SQL的語法。對於字段名,建議使用主鍵之外的字段,如果使用了INTEGER類型的主鍵字段,執行類似insert into person(personid) values(NULL)的insert語句後,該主鍵字段值也不會為NULL。如果第三個參數values 不為Null並且元素的個數大於0 ,可以把第二個參數設置為null。


delete()方法的使用:
SQLiteDatabase db = databaseHelper.getWritableDatabase();
db.delete("person", "personid<?", new String[]{"2"});
db.close();
上面代碼用於從person表中刪除personid小於2的記錄。

update()方法的使用:
SQLiteDatabase db = databaseHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(“name”, “csdn”);//key為字段名,value為值
db.update("person", values, "personid=?", new String[]{"1"});
db.close();
上面代碼用於把person表中personid等於1的記錄的name字段的值改為“傳智播客”。
query()方法實際上是把select語句拆分成了若干個組成部分,然後作為方法的輸入參數:
SQLiteDatabase db = databaseHelper.getWritableDatabase();
Cursor cursor = db.query("person", new String[]{"personid,name,age"}, "name like ?", new String[]{"%cs%"}, null, null, "personid desc", "1,2");
while (cursor.moveToNext()) {
int personid = cursor.getInt(0); //獲取第一列的值,第一列的索引從0開始
String name = cursor.getString(1);//獲取第二列的值
int age = cursor.getInt(2);//獲取第三列的值
}
cursor.close();
db.close();
上面代碼用於從person表中查找name字段含有“傳智”的記錄,匹配的記錄按personid降序排序,對排序後的結果略過第一條記錄,只獲取2條記錄。
query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit)方法各參數的含義:
table:表名。相當於select語句from關鍵字後面的部分。如果是多表聯合查詢,可以用逗號將兩個表名分開。
columns:要查詢出來的列名。相當於select語句select關鍵字後面的部分。
selection:查詢條件子句,相當於select語句where關鍵字後面的部分,在條件子句允許使用占位符“?”
selectionArgs:對應於selection語句中占位符的值,值在數組中的位置與占位符在語句中的位置必須一致,否則就會有異常。
groupBy:相當於select語句group by關鍵字後面的部分
having:相當於select語句having關鍵字後面的部分
orderBy:相當於select語句order by關鍵字後面的部分,如:personid desc, age asc;
limit:指定偏移量和獲取的記錄數,相當於select語句limit關鍵字後面的部分。

 

\

代碼示例:

1、寫一個DBSQLiteHelper類繼承SQLiteOpenHelper

[java]
package com.example.lession05_dbs.dbs;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBSQLiteHelper extends SQLiteOpenHelper {

private static final String tag="DBSQLiteHelper";

private static final String name="csdn.db";
private static final int version=1;

public DBSQLiteHelper(Context context) {
super(context, name, null, version);
Log.v(tag, "構造器");
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table person(id integer primary key autoincrement,name varchar(20),age integer)");
Log.v(tag, "數據庫創建執行一次");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {


}

}
[java]
package com.example.lession05_dbs.dbs; 
 
import android.content.Context; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteOpenHelper; 
import android.util.Log; 
 
public class DBSQLiteHelper extends SQLiteOpenHelper { 
     
    private static final String tag="DBSQLiteHelper"; 
     
    private static final String name="csdn.db"; 
    private static final int version=1; 
 
    public DBSQLiteHelper(Context context) { 
        super(context, name, null, version); 
        Log.v(tag, "構造器"); 
    } 
 
    @Override 
    public void onCreate(SQLiteDatabase db) { 
        db.execSQL("create table person(id integer primary key autoincrement,name varchar(20),age integer)"); 
        Log.v(tag, "數據庫創建執行一次"); 
         
    } 
 
    @Override 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
         
         
    } 
 

package com.example.lession05_dbs.dbs;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBSQLiteHelper extends SQLiteOpenHelper {
 
 private static final String tag="DBSQLiteHelper";
 
 private static final String name="csdn.db";
 private static final int version=1;

 public DBSQLiteHelper(Context context) {
  super(context, name, null, version);
  Log.v(tag, "構造器");
 }

 @Override
 public void onCreate(SQLiteDatabase db) {
  db.execSQL("create table person(id integer primary key autoincrement,name varchar(20),age integer)");
  Log.v(tag, "數據庫創建執行一次");
  
 }

 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  
  
 }

}

 

2、根據創建的表寫一個實體bean

[java]
package com.example.lession05_dbs.domain;

import java.io.Serializable;

public class Person implements Serializable{

/**
*
*/
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
public Person() {
super();
// TODO Auto-generated constructor stub
}
public Person(Integer id, String name, Integer age) {
super();
this.id = id;
this.name = name;
this.age = age;
}


}
[java]
package com.example.lession05_dbs.domain; 
 
import java.io.Serializable; 
 
public class Person implements Serializable{ 
 
    /**
     * 
     */ 
    private static final long serialVersionUID = 1L; 
    private Integer id; 
    private String name; 
    private Integer age; 
    public Integer getId() { 
        return id; 
    } 
    public void setId(Integer id) { 
        this.id = id; 
    } 
    public String getName() { 
        return name; 
    } 
    public void setName(String name) { 
        this.name = name; 
    } 
    public Integer getAge() { 
        return age; 
    } 
    public void setAge(Integer age) { 
        this.age = age; 
    } 
    @Override 
    public String toString() { 
        return "Person [id=" + id + ", name=" + name + ", age=" + age + "]"; 
    } 
    public Person() { 
        super(); 
        // TODO Auto-generated constructor stub  
    } 
    public Person(Integer id, String name, Integer age) { 
        super(); 
        this.id = id; 
        this.name = name; 
        this.age = age; 
    } 
     
     

package com.example.lession05_dbs.domain;

import java.io.Serializable;

public class Person implements Serializable{

 /**
  *
  */
 private static final long serialVersionUID = 1L;
 private Integer id;
 private String name;
 private Integer age;
 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public Integer getAge() {
  return age;
 }
 public void setAge(Integer age) {
  this.age = age;
 }
 @Override
 public String toString() {
  return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
 }
 public Person() {
  super();
  // TODO Auto-generated constructor stub
 }
 public Person(Integer id, String name, Integer age) {
  super();
  this.id = id;
  this.name = name;
  this.age = age;
 }
 
 
}

3、寫一個接口,裡面有增刪改查的方法

[java]
package com.example.lession05_dbs.dao;

import java.util.List;

import com.example.lession05_dbs.domain.Person;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;

public interface PersonDao {

//添加的操作
public boolean insert(SQLiteDatabase db,ContentValues values);
//執行更新的操作
public boolean update(SQLiteDatabase db,ContentValues values,Integer id);
//根據id刪除操作
public boolean delete(SQLiteDatabase db,Integer id);
//查詢所有
public List<Person> findAll(SQLiteDatabase db);
//條件查詢操作
public List<Person> findByName(SQLiteDatabase db,String[] selectionArgs);
//獲取當前頁的信息
public List<Person> getNowPageInfo(SQLiteDatabase db,String[] selectionArgs,String order,String limit);
}
[java]
package com.example.lession05_dbs.dao; 
 
import java.util.List; 
 
import com.example.lession05_dbs.domain.Person; 
 
import android.content.ContentValues; 
import android.database.sqlite.SQLiteDatabase; 
 
public interface PersonDao { 
 
    //添加的操作  
    public boolean insert(SQLiteDatabase db,ContentValues values); 
    //執行更新的操作  
    public boolean update(SQLiteDatabase db,ContentValues values,Integer id); 
    //根據id刪除操作  
    public boolean delete(SQLiteDatabase db,Integer id); 
    //查詢所有  
    public List<Person> findAll(SQLiteDatabase db); 
    //條件查詢操作  
    public List<Person> findByName(SQLiteDatabase db,String[] selectionArgs); 
    //獲取當前頁的信息  
    public List<Person> getNowPageInfo(SQLiteDatabase db,String[] selectionArgs,String order,String limit); 

package com.example.lession05_dbs.dao;

import java.util.List;

import com.example.lession05_dbs.domain.Person;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;

public interface PersonDao {

 //添加的操作
 public boolean insert(SQLiteDatabase db,ContentValues values);
 //執行更新的操作
 public boolean update(SQLiteDatabase db,ContentValues values,Integer id);
 //根據id刪除操作
 public boolean delete(SQLiteDatabase db,Integer id);
 //查詢所有
 public List<Person> findAll(SQLiteDatabase db);
 //條件查詢操作
 public List<Person> findByName(SQLiteDatabase db,String[] selectionArgs);
 //獲取當前頁的信息
 public List<Person> getNowPageInfo(SQLiteDatabase db,String[] selectionArgs,String order,String limit);
}

 

4、寫一個實現類實現該接口

[java]
package com.example.lession05_dbs.dao;

import java.util.ArrayList;
import java.util.List;

import com.example.lession05_dbs.domain.Person;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class PersonDaoImpl implements PersonDao {

@Override
public boolean insert(SQLiteDatabase db, ContentValues values) {
boolean flag=false;
if(db.isOpen()){
long l=db.insert("person",null, values);

/**
* table 表名 nullColumnHack: insert into
* person(name,phone)values('chenhj','123'); //insert into
* person(name) values(null); //insert into person() values();
* values 參數
*
*/
if(l>0){
flag=true;
}
db.close();
}
return flag;
}

@Override
public boolean update(SQLiteDatabase db, ContentValues values, Integer id) {
boolean flag=false;
if(db.isOpen()){
long l=db.update("person", values, "id=?", new String[]{id+""});
if(l>0){
flag=true;
}
db.close();
}
return flag;
}

@Override
public boolean delete(SQLiteDatabase db, Integer id) {
boolean flag=false;
if(db.isOpen()){
long l=db.delete("person", "id=?", new String[]{id+""});
if(l>0){
flag=true;
}
}
return flag;
}

@Override
public List<Person> findAll(SQLiteDatabase db) {
List<Person> persons=new ArrayList<Person>();
if(db.isOpen()){
Cursor cursor=db.query("person", new String[] { "id", "name",
"age" }, null, null, null, null, null);

while(cursor.moveToNext()){
Person person=new Person();

person.setId(cursor.getInt(cursor.getColumnIndex("id")));
person.setName(cursor.getString(cursor.getColumnIndex("name")));
person.setAge(cursor.getInt(cursor.getColumnIndex("age")));

persons.add(person);
}
}
return persons;
}

@Override
public List<Person> findByName(SQLiteDatabase db, String[] selectionArgs) {
List<Person> persons=new ArrayList<Person>();
if (db.isOpen()) {
// 執行查詢
Cursor cursor = db.query("person", new String[] { "id", "name","age" }, "name like ?", selectionArgs, null, null, "id desc");

while (cursor.moveToNext()) {
// 創建person對象
Person person = new Person();
// 設置person的屬性
person.setId(cursor.getInt(cursor.getColumnIndex("id")));
person.setName(cursor.getString(cursor.getColumnIndex("name")));
person.setAge(cursor.getInt(cursor.getColumnIndex("age")));
// 添加到集合眾
persons.add(person);
}
}

return persons;
}

@Override
public List<Person> getNowPageInfo(SQLiteDatabase db,
String[] selectionArgs, String order, String limit) {

List<Person> persons = new ArrayList<Person>();

if (db.isOpen()) {
// 執行查詢
Cursor cursor = db.query("person", new String[] { "id", "name","age" }, "name like ?", selectionArgs, null, null, order,limit);

while (cursor.moveToNext()) {
// 創建person對象
Person person = new Person();
// 設置person的屬性
person.setId(cursor.getInt(cursor.getColumnIndex("id")));
person.setName(cursor.getString(cursor.getColumnIndex("name")));
person.setAge(cursor.getInt(cursor.getColumnIndex("age")));
// 添加到集合眾
persons.add(person);
}
}

return persons;
}

}
[java]
package com.example.lession05_dbs.dao; 
 
import java.util.ArrayList; 
import java.util.List; 
 
import com.example.lession05_dbs.domain.Person; 
 
import android.content.ContentValues; 
import android.database.Cursor; 
import android.database.sqlite.SQLiteDatabase; 
 
public class PersonDaoImpl implements PersonDao { 
 
    @Override 
    public boolean insert(SQLiteDatabase db, ContentValues values) { 
        boolean flag=false; 
        if(db.isOpen()){ 
            long l=db.insert("person",null, values); 
             
            /**
             * table 表名 nullColumnHack: insert into
             * person(name,phone)values('chenhj','123'); //insert into
             * person(name) values(null); //insert into person() values();
             * values 參數
             * 
             */ 
            if(l>0){ 
                flag=true; 
            } 
            db.close(); 
        } 
        return flag; 
    } 
 
    @Override 
    public boolean update(SQLiteDatabase db, ContentValues values, Integer id) { 
        boolean flag=false; 
        if(db.isOpen()){ 
            long l=db.update("person", values, "id=?", new String[]{id+""}); 
            if(l>0){ 
                flag=true; 
            } 
            db.close(); 
        } 
        return flag; 
    } 
 
    @Override 
    public boolean delete(SQLiteDatabase db, Integer id) { 
        boolean flag=false; 
        if(db.isOpen()){ 
            long l=db.delete("person", "id=?", new String[]{id+""}); 
            if(l>0){ 
                flag=true; 
            } 
        } 
        return flag; 
    } 
 
    @Override 
    public List<Person> findAll(SQLiteDatabase db) { 
        List<Person> persons=new ArrayList<Person>(); 
        if(db.isOpen()){ 
            Cursor cursor=db.query("person", new String[] { "id", "name", 
            "age" }, null, null, null, null, null); 
             
            while(cursor.moveToNext()){ 
                Person person=new Person(); 
                 
                person.setId(cursor.getInt(cursor.getColumnIndex("id"))); 
                person.setName(cursor.getString(cursor.getColumnIndex("name"))); 
                person.setAge(cursor.getInt(cursor.getColumnIndex("age"))); 
                 
                persons.add(person); 
            } 
        } 
        return persons; 
    } 
 
    @Override 
    public List<Person> findByName(SQLiteDatabase db, String[] selectionArgs) { 
        List<Person> persons=new ArrayList<Person>(); 
        if (db.isOpen()) { 
            // 執行查詢  
            Cursor cursor = db.query("person", new String[] { "id", "name","age" }, "name like ?", selectionArgs, null, null, "id desc"); 
             
            while (cursor.moveToNext()) { 
                // 創建person對象  
                Person person = new Person(); 
                // 設置person的屬性  
                person.setId(cursor.getInt(cursor.getColumnIndex("id"))); 
                person.setName(cursor.getString(cursor.getColumnIndex("name"))); 
                person.setAge(cursor.getInt(cursor.getColumnIndex("age"))); 
                // 添加到集合眾  
                persons.add(person); 
            } 
        } 
         
        return persons; 
    } 
 
    @Override 
    public List<Person> getNowPageInfo(SQLiteDatabase db, 
            String[] selectionArgs, String order, String limit) { 
         
        List<Person> persons = new ArrayList<Person>(); 
         
        if (db.isOpen()) { 
            // 執行查詢  
            Cursor cursor = db.query("person", new String[] { "id", "name","age" }, "name like ?", selectionArgs, null, null, order,limit); 
             
            while (cursor.moveToNext()) { 
                // 創建person對象  
                Person person = new Person(); 
                // 設置person的屬性  
                person.setId(cursor.getInt(cursor.getColumnIndex("id"))); 
                person.setName(cursor.getString(cursor.getColumnIndex("name"))); 
                person.setAge(cursor.getInt(cursor.getColumnIndex("age"))); 
                // 添加到集合眾  
                persons.add(person); 
            } 
        } 
         
        return persons; 
    } 
 

package com.example.lession05_dbs.dao;

import java.util.ArrayList;
import java.util.List;

import com.example.lession05_dbs.domain.Person;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class PersonDaoImpl implements PersonDao {

 @Override
 public boolean insert(SQLiteDatabase db, ContentValues values) {
  boolean flag=false;
  if(db.isOpen()){
   long l=db.insert("person",null, values);
   
   /**
    * table 表名 nullColumnHack: insert into
    * person(name,phone)values('chenhj','123'); //insert into
    * person(name) values(null); //insert into person() values();
    * values 參數
    *
    */
   if(l>0){
    flag=true;
   }
   db.close();
  }
  return flag;
 }

 @Override
 public boolean update(SQLiteDatabase db, ContentValues values, Integer id) {
  boolean flag=false;
  if(db.isOpen()){
   long l=db.update("person", values, "id=?", new String[]{id+""});
   if(l>0){
    flag=true;
   }
   db.close();
  }
  return flag;
 }

 @Override
 public boolean delete(SQLiteDatabase db, Integer id) {
  boolean flag=false;
  if(db.isOpen()){
   long l=db.delete("person", "id=?", new String[]{id+""});
   if(l>0){
    flag=true;
   }
  }
  return flag;
 }

 @Override
 public List<Person> findAll(SQLiteDatabase db) {
  List<Person> persons=new ArrayList<Person>();
  if(db.isOpen()){
   Cursor cursor=db.query("person", new String[] { "id", "name",
   "age" }, null, null, null, null, null);
   
   while(cursor.moveToNext()){
    Person person=new Person();
    
    person.setId(cursor.getInt(cursor.getColumnIndex("id")));
    person.setName(cursor.getString(cursor.getColumnIndex("name")));
    person.setAge(cursor.getInt(cursor.getColumnIndex("age")));
    
    persons.add(person);
   }
  }
  return persons;
 }

 @Override
 public List<Person> findByName(SQLiteDatabase db, String[] selectionArgs) {
  List<Person> persons=new ArrayList<Person>();
  if (db.isOpen()) {
   // 執行查詢
   Cursor cursor = db.query("person", new String[] { "id", "name","age" }, "name like ?", selectionArgs, null, null, "id desc");
   
   while (cursor.moveToNext()) {
    // 創建person對象
    Person person = new Person();
    // 設置person的屬性
    person.setId(cursor.getInt(cursor.getColumnIndex("id")));
    person.setName(cursor.getString(cursor.getColumnIndex("name")));
    person.setAge(cursor.getInt(cursor.getColumnIndex("age")));
    // 添加到集合眾
    persons.add(person);
   }
  }
  
  return persons;
 }

 @Override
 public List<Person> getNowPageInfo(SQLiteDatabase db,
   String[] selectionArgs, String order, String limit) {
  
  List<Person> persons = new ArrayList<Person>();
  
  if (db.isOpen()) {
   // 執行查詢
   Cursor cursor = db.query("person", new String[] { "id", "name","age" }, "name like ?", selectionArgs, null, null, order,limit);
   
   while (cursor.moveToNext()) {
    // 創建person對象
    Person person = new Person();
    // 設置person的屬性
    person.setId(cursor.getInt(cursor.getColumnIndex("id")));
    person.setName(cursor.getString(cursor.getColumnIndex("name")));
    person.setAge(cursor.getInt(cursor.getColumnIndex("age")));
    // 添加到集合眾
    persons.add(person);
   }
  }
  
  return persons;
 }

}

5、寫一個測試類

首先在項目清單中添加

[html]
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lession05_dbs"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<instrumentation android:targetPackage="com.example.lession05_dbs" android:name="android.test.InstrumentationTestRunner"></instrumentation>

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.lession05_dbs.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>
<uses-library android:name="android.test.runner"/>
</application>

</manifest>
[html]
<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.lession05_dbs" 
    android:versionCode="1" 
    android:versionName="1.0" > 
 
    <uses-sdk 
        android:minSdkVersion="8" 
        android:targetSdkVersion="17" /> 
    <instrumentation android:targetPackage="com.example.lession05_dbs" android:name="android.test.InstrumentationTestRunner"></instrumentation> 
 
    <application 
        android:allowBackup="true" 
        android:icon="@drawable/ic_launcher" 
        android:label="@string/app_name" 
        android:theme="@style/AppTheme" > 
        <activity 
            android:name="com.example.lession05_dbs.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> 
        <uses-library android:name="android.test.runner"/> 
    </application> 
 
</manifest> 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.lession05_dbs"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <instrumentation android:targetPackage="com.example.lession05_dbs" android:name="android.test.InstrumentationTestRunner"></instrumentation>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.lession05_dbs.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>
        <uses-library android:name="android.test.runner"/>
    </application>

</manifest>

其次寫代碼進行測試

[java]
package com.example.lession05_dbs.test;

import java.util.List;

import com.example.lession05_dbs.dao.PersonDao;
import com.example.lession05_dbs.dao.PersonDaoImpl;
import com.example.lession05_dbs.dbs.DBSQLiteHelper;
import com.example.lession05_dbs.domain.Person;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.test.AndroidTestCase;

public class DBTest extends AndroidTestCase{

PersonDao personDao=new PersonDaoImpl();

public void createDB(){
DBSQLiteHelper db=new DBSQLiteHelper(this.getContext());
SQLiteDatabase sdb=db.getWritableDatabase();
}

public void insert(){
DBSQLiteHelper db=new DBSQLiteHelper(this.getContext());
for(int i=1;i<10;i++){
SQLiteDatabase sdb=db.getWritableDatabase();

ContentValues values=new ContentValues();
Person person=new Person(null, "shuang"+i, 21);

values.put("name", person.getName());
values.put("age",person.getAge());

personDao.insert(sdb, values);
}
}

public void update(){
DBSQLiteHelper db=new DBSQLiteHelper(this.getContext());
SQLiteDatabase sdb=db.getWritableDatabase();

ContentValues values=new ContentValues();
Person person=new Person(1,"xue",22);

values.put("name", person.getName());
values.put("age", person.getAge());

personDao.update(sdb, values, person.getId());
}

public void delete(){
DBSQLiteHelper db=new DBSQLiteHelper(this.getContext());
SQLiteDatabase sdb=db.getWritableDatabase();
Person person=new Person(1,"xue",22);
personDao.delete(sdb, person.getId());
}

public void findAll(){
DBSQLiteHelper db=new DBSQLiteHelper(this.getContext());
SQLiteDatabase sdb=db.getWritableDatabase();

List<Person> persons=personDao.findAll(sdb);
for(Person p:persons){
System.out.println(p.toString());
}
}

public void findByName(){
DBSQLiteHelper db=new DBSQLiteHelper(this.getContext());
SQLiteDatabase sdb=db.getWritableDatabase();

List<Person> persons=personDao.findByName(sdb, new String[]{"%g1%"});
for(Person p:persons){
System.out.println(p.toString());
}
}

public void getPage(){
DBSQLiteHelper db=new DBSQLiteHelper(this.getContext());
SQLiteDatabase sdb=db.getWritableDatabase();

List<Person> persons=personDao.getNowPageInfo(sdb, new String[]{"%sh%"}, " id desc ", "0,3");
for(Person p:persons){
System.out.println(p.toString());
}
}
}
[java]
package com.example.lession05_dbs.test; 
 
import java.util.List; 
 
import com.example.lession05_dbs.dao.PersonDao; 
import com.example.lession05_dbs.dao.PersonDaoImpl; 
import com.example.lession05_dbs.dbs.DBSQLiteHelper; 
import com.example.lession05_dbs.domain.Person; 
 
import android.content.ContentValues; 
import android.database.sqlite.SQLiteDatabase; 
import android.test.AndroidTestCase; 
 
public class DBTest extends AndroidTestCase{ 
 
    PersonDao personDao=new PersonDaoImpl(); 
     
    public void createDB(){ 
        DBSQLiteHelper db=new DBSQLiteHelper(this.getContext()); 
        SQLiteDatabase sdb=db.getWritableDatabase(); 
    } 
     
    public void insert(){ 
        DBSQLiteHelper db=new DBSQLiteHelper(this.getContext()); 
        for(int i=1;i<10;i++){ 
            SQLiteDatabase sdb=db.getWritableDatabase(); 
             
            ContentValues values=new ContentValues(); 
            Person person=new Person(null, "shuang"+i, 21); 
             
            values.put("name", person.getName()); 
            values.put("age",person.getAge()); 
             
            personDao.insert(sdb, values); 
        } 
    } 
     
    public void update(){ 
        DBSQLiteHelper db=new DBSQLiteHelper(this.getContext()); 
        SQLiteDatabase sdb=db.getWritableDatabase(); 
         
        ContentValues values=new ContentValues(); 
        Person person=new Person(1,"xue",22); 
         
        values.put("name", person.getName()); 
        values.put("age", person.getAge()); 
         
        personDao.update(sdb, values, person.getId()); 
    } 
     
    public void delete(){ 
        DBSQLiteHelper db=new DBSQLiteHelper(this.getContext()); 
        SQLiteDatabase sdb=db.getWritableDatabase(); 
        Person person=new Person(1,"xue",22); 
        personDao.delete(sdb, person.getId()); 
    } 
     
    public void findAll(){ 
        DBSQLiteHelper db=new DBSQLiteHelper(this.getContext()); 
        SQLiteDatabase sdb=db.getWritableDatabase(); 
         
        List<Person> persons=personDao.findAll(sdb); 
        for(Person p:persons){ 
            System.out.println(p.toString()); 
        } 
    } 
     
    public void findByName(){ 
        DBSQLiteHelper db=new DBSQLiteHelper(this.getContext()); 
        SQLiteDatabase sdb=db.getWritableDatabase(); 
         
        List<Person> persons=personDao.findByName(sdb, new String[]{"%g1%"}); 
        for(Person p:persons){ 
            System.out.println(p.toString()); 
        } 
    } 
     
    public void getPage(){ 
        DBSQLiteHelper db=new DBSQLiteHelper(this.getContext()); 
        SQLiteDatabase sdb=db.getWritableDatabase(); 
         
        List<Person> persons=personDao.getNowPageInfo(sdb, new String[]{"%sh%"}, " id desc ", "0,3"); 
        for(Person p:persons){ 
            System.out.println(p.toString()); 
        } 
    } 

package com.example.lession05_dbs.test;

import java.util.List;

import com.example.lession05_dbs.dao.PersonDao;
import com.example.lession05_dbs.dao.PersonDaoImpl;
import com.example.lession05_dbs.dbs.DBSQLiteHelper;
import com.example.lession05_dbs.domain.Person;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.test.AndroidTestCase;

public class DBTest extends AndroidTestCase{

 PersonDao personDao=new PersonDaoImpl();
 
 public void createDB(){
  DBSQLiteHelper db=new DBSQLiteHelper(this.getContext());
  SQLiteDatabase sdb=db.getWritableDatabase();
 }
 
 public void insert(){
  DBSQLiteHelper db=new DBSQLiteHelper(this.getContext());
  for(int i=1;i<10;i++){
   SQLiteDatabase sdb=db.getWritableDatabase();
   
   ContentValues values=new ContentValues();
   Person person=new Person(null, "shuang"+i, 21);
   
   values.put("name", person.getName());
   values.put("age",person.getAge());
   
   personDao.insert(sdb, values);
  }
 }
 
 public void update(){
  DBSQLiteHelper db=new DBSQLiteHelper(this.getContext());
  SQLiteDatabase sdb=db.getWritableDatabase();
  
  ContentValues values=new ContentValues();
  Person person=new Person(1,"xue",22);
  
  values.put("name", person.getName());
  values.put("age", person.getAge());
  
  personDao.update(sdb, values, person.getId());
 }
 
 public void delete(){
  DBSQLiteHelper db=new DBSQLiteHelper(this.getContext());
  SQLiteDatabase sdb=db.getWritableDatabase();
  Person person=new Person(1,"xue",22);
  personDao.delete(sdb, person.getId());
 }
 
 public void findAll(){
  DBSQLiteHelper db=new DBSQLiteHelper(this.getContext());
  SQLiteDatabase sdb=db.getWritableDatabase();
  
  List<Person> persons=personDao.findAll(sdb);
  for(Person p:persons){
   System.out.println(p.toString());
  }
 }
 
 public void findByName(){
  DBSQLiteHelper db=new DBSQLiteHelper(this.getContext());
  SQLiteDatabase sdb=db.getWritableDatabase();
  
  List<Person> persons=personDao.findByName(sdb, new String[]{"%g1%"});
  for(Person p:persons){
   System.out.println(p.toString());
  }
 }
 
 public void getPage(){
  DBSQLiteHelper db=new DBSQLiteHelper(this.getContext());
  SQLiteDatabase sdb=db.getWritableDatabase();
  
  List<Person> persons=personDao.getNowPageInfo(sdb, new String[]{"%sh%"}, " id desc ", "0,3");
  for(Person p:persons){
   System.out.println(p.toString());
  }
 }
}

 

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved