2025-05-23

SQLite是Android使用的輕量級的數據庫,開發Android應用是對數據庫的操作自然是必不可少。

Android提供瞭一個SQLiteOpenHelper類來可以很方便的操作數據庫,

繼承和擴展SQLiteOpenHelper類主要做的工作就是重寫以下兩個方法。
       onCreate: 當數據庫被首次創建時執行該方法,一般將創建表等初始化操作在該方法中執行。
       onUpgrade:當打開數據庫時傳入的版本號與當前的版本號不同時會調用該方法。

 

下面是我寫的一個SQLite基本操作的demo。

 

主要包含兩個java類——

DBUtil類,繼承自SQLiteOpenHelper,用以實現各種操作功能:

[java]
package barry.android.db; 
 
import android.content.ContentValues; 
import android.content.Context; 
import android.database.Cursor; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteOpenHelper; 
 
public class DBUtil extends SQLiteOpenHelper { 
 
    private final static String DATABASE_NAME = "db2004"; 
    private final static int DATABASE_VERSION = 1; 
    private static final String TABLE_NAME ="students"; 
    private static final String FILED_1 = "name"; 
    private static final String FILED_2 = "password"; 
 
    public DBUtil(Context context){ 
        super(context, DATABASE_NAME,null,DATABASE_VERSION); 
        System.out.println("new DBUtil"); 
    } 
 
    @Override 
    public void onCreate(SQLiteDatabase db) { 
        String sql = "CREATE TABLE "+TABLE_NAME+" ( "+FILED_1 +" TEXT, "+ FILED_2 +" TEXT );"; 
        db.execSQL(sql); 
        System.out.println("oncreate創建表"); 
    } 
 
    @Override 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
        db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME); 
        System.out.println("onUpgrade刪除表"); 
        this.onCreate(db); 
    } 
     
    /**
     * 查詢表中所有的數據
     * @return
     */ 
    public Cursor select(){ 
        return this.getReadableDatabase() 
            .query(TABLE_NAME, null, null, null, null, null, null);      
    } 
 
    /**
     * 插入一條數據到表中
     * @param name 字段一的值
     * @param password 字段二的值
     */ 
    public void insert(String name ,String password){ 
        ContentValues cv = new ContentValues(); 
        cv.put(FILED_1, name); 
        cv.put(FILED_2, password);       
        this.getWritableDatabase().insert(TABLE_NAME, null, cv); 
        this.getWritableDatabase().close();//關閉數據庫對象   
    }    
     
    /**
     * 刪除表中的若幹條數據
     * @param name 一個包含所有要刪除數據的"name"字段的數組
     */ 
    public void delete(String[] name){ 
        String where = FILED_1+" = ?"; 
        String[] whereValues = name;  
        this.getWritableDatabase().delete(TABLE_NAME, where, whereValues); 
        this.getWritableDatabase().close(); 
    } 
     
    /**
     * 更新表中的數據(修改字段二"password")
     * @param name 要更新的數據"name"字段值
     * @param newPassword 新的"password"字段
     */ 
    public void update(String name,String newPassword){      
        ContentValues cv = new ContentValues(); 
        cv.put(FILED_2, newPassword);        
        String where =FILED_1+" = ?"; 
        String[] whereValues= {name};        
        this.getWritableDatabase().update(TABLE_NAME, cv, where, whereValues); 
        this.getWritableDatabase().close(); 
    }    
     
    /**
     * 清空表中的數據
     */ 
    public void clean (){ 
        this.getWritableDatabase().execSQL("DROP TABLE IF EXISTS "+TABLE_NAME); 
        System.out.println("clean刪除表"); 
        this.onCreate(this.getWritableDatabase()); 
        this.getWritableDatabase().close(); 
    } 

package barry.android.db;

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

public class DBUtil extends SQLiteOpenHelper {

 private final static String DATABASE_NAME = "db2004";
 private final static int DATABASE_VERSION = 1;
 private static final String TABLE_NAME ="students";
 private static final String FILED_1 = "name";
 private static final String FILED_2 = "password";

 public DBUtil(Context context){
  super(context, DATABASE_NAME,null,DATABASE_VERSION);
  System.out.println("new DBUtil");
 }

 @Override
 public void onCreate(SQLiteDatabase db) {
  String sql = "CREATE TABLE "+TABLE_NAME+" ( "+FILED_1 +" TEXT, "+ FILED_2 +" TEXT );";
  db.execSQL(sql);
  System.out.println("oncreate創建表");
 }

 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
  System.out.println("onUpgrade刪除表");
  this.onCreate(db);
 }
 
 /**
  * 查詢表中所有的數據
  * @return
  */
 public Cursor select(){
  return this.getReadableDatabase()
   .query(TABLE_NAME, null, null, null, null, null, null);  
 }

 /**
  * 插入一條數據到表中www.aiwalls.com
  * @param name 字段一的值
  * @param password 字段二的值
  */
 public void insert(String name ,String password){
  ContentValues cv = new ContentValues();
  cv.put(FILED_1, name);
  cv.put(FILED_2, password);  
  this.getWritableDatabase().insert(TABLE_NAME, null, cv);
  this.getWritableDatabase().close();//關閉數據庫對象
 } 
 
 /**
  * 刪除表中的若幹條數據
  * @param name 一個包含所有要刪除數據的"name"字段的數組
  */
 public void delete(String[] name){
  String where = FILED_1+" = ?";
  String[] whereValues = name;
  this.getWritableDatabase().delete(TABLE_NAME, where, whereValues);
  this.getWritableDatabase().close();
 }
 
 /**
  * 更新表中的數據(修改字段二"password")
  * @param name 要更新的數據"name"字段值
  * @param newPassword 新的"password"字段
  */
 public void update(String name,String newPassword){  
  ContentValues cv = new ContentValues();
  cv.put(FILED_2, newPassword);  
  String where =FILED_1+" = ?";
  String[] whereValues= {name};  
  this.getWritableDatabase().update(TABLE_NAME, cv, where, whereValues);
  this.getWritableDatabase().close();
 } 
 
 /**
  * 清空表中的數據
  */
 public void clean (){
  this.getWritableDatabase().execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
  System.out.println("clean刪除表");
  this.onCreate(this.getWritableDatabase());
  this.getWritableDatabase().close();
 }
}

 

以及調用DBUtil的Activity:

[java]
package barry.android.db; 
 
import android.app.Activity; 
import android.database.Cursor; 
import android.os.Bundle; 
 
public class Demo04_helperActivity extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
         
         
        DBUtil dbUtil = new DBUtil(this); 
        dbUtil.insert("周傑倫", "jaychou"); 
        dbUtil.insert("韓寒", "twocolds"); 
        dbUtil.insert("郭德綱", "yunhejiuxiao");         
         
        System.out.println("***********************************全部數據息"); 
        printData(dbUtil);         
         
        dbUtil.delete(new String[]{"周傑倫"}); 
         
        System.out.println("***********************************刪除'周傑倫'之後數據"); 
        printData(dbUtil);  
         
        dbUtil.update("郭德綱", "longtengsihai");; 
        System.out.println("***********************************修改‘郭德綱’的密碼為'longtengsihai'"); 
        printData(dbUtil);  
         
        dbUtil.clean(); 
         
    } 
 
    private void printData(DBUtil dbUtil) { 
        Cursor cursor = dbUtil.select();         
        if(cursor.moveToFirst()){ 
            System.out.println("當前表中的數據條數:"+cursor.getCount()); 
            do{ 
                System.out.println(cursor.getString(0)+cursor.getString(1));                 
            }while(cursor.moveToNext()); 
        } 
        cursor.close(); 
    } 

package barry.android.db;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;

public class Demo04_helperActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
       
        DBUtil dbUtil = new DBUtil(this);
        dbUtil.insert("周傑倫", "jaychou");
        dbUtil.insert("韓寒", "twocolds");
        dbUtil.insert("郭德綱", "yunhejiuxiao");       
       
        System.out.println("***********************************全部數據息");
        printData(dbUtil);       
       
        dbUtil.delete(new String[]{"周傑倫"});
       
        System.out.println("***********************************刪除'周傑倫'之後數據");
        printData(dbUtil);
       
        dbUtil.update("郭德綱", "longtengsihai");;
        System.out.println("***********************************修改‘郭德綱’的密碼為'longtengsihai'");
        printData(dbUtil);
       
        dbUtil.clean();
       
    }

 private void printData(DBUtil dbUtil) {
  Cursor cursor = dbUtil.select();       
  if(cursor.moveToFirst()){
   System.out.println("當前表中的數據條數:"+cursor.getCount());
   do{
    System.out.println(cursor.getString(0)+cursor.getString(1));    
   }while(cursor.moveToNext());
  }
  cursor.close();
 }
}
該程序所執行的操作為:

1.在創建一個名為"db2004"的數據庫,(即DBUtil的“DATABASE_NAME”字段)。

2.當數據庫被首次創建時執行DBUtil的onCreate方法,創建一張名為students的表,包含兩個字段(name,password)。(即DBUtil的”TABLE_NAME、FILED_1、FILED_2”字段)。

3.往數據庫中插入三條數據“周傑倫、韓寒、郭德綱”。然後.查詢出表中所有數據並打印。

4.刪除數據“周傑倫”。然後.查詢出表中所有數據並打印。

5.將數據“郭德綱”的password修改為"longtengsihai"。然後.查詢出表中所有數據並打印。

6.清除表中的所有數據,程序結束。

執行的結果為:

02-07 11:22:47.361: I/System.out(962): new DBUtil
02-07 11:22:47.490: I/System.out(962): ***********************************全部數據息
02-07 11:22:47.490: I/System.out(962): 當前表中的數據條數:3
02-07 11:22:47.500: I/System.out(962): 周傑倫jaychou
02-07 11:22:47.500: I/System.out(962): 韓寒twocolds
02-07 11:22:47.500: I/System.out(962): 郭德綱yunhejiuxiao
02-07 11:22:47.511: I/System.out(962): ***********************************刪除'周傑倫'之後數據
02-07 11:22:47.540: I/System.out(962): 當前表中的數據條數:2
02-07 11:22:47.540: I/System.out(962): 韓寒twocolds
02-07 11:22:47.550: I/System.out(962): 郭德綱yunhejiuxiao
02-07 11:22:47.560: I/System.out(962): ***********************************修改‘郭德綱’的密碼為'longtengsihai'
02-07 11:22:47.590: I/System.out(962): 當前表中的數據條數:2
02-07 11:22:47.590: I/System.out(962): 韓寒twocolds
02-07 11:22:47.590: I/System.out(962): 郭德綱longtengsihai
02-07 11:22:47.601: I/System.out(962): clean刪除表
02-07 11:22:47.610: I/System.out(962): oncreate創建表

結果正確。

 

摘自  狼的第二個小窩
 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *