使用SQLiteOpenHelper和单例模式操作SQLite数据库

在前文中总结了SQLite数据库的基本用法,本文中将使用SQLiteOpenHelper和单例模式来操作数据库。SQLiteOpenHelper是Android提供的一个管理数据库的工具类,可以用于管理数据库的创建和版本更新。一般的用法是创建它的子类,并扩展它的onCreate()和onUpgrade方法。

SQLiteOpenHelper包含如下方法:

同上文一样,数据仍是手动写死的,实际情况应该根据业务需求从界面或其他地方获取,实例代码如下,关键是后面两个类:

Activity:

[java]  view plain copy
  1. package com.lovo.activity;  
  2.   
  3. import android.app.Activity;  
  4. import android.database.Cursor;  
  5. import android.os.Bundle;  
  6. import android.view.View;  
  7. import android.widget.TextView;  
  8.   
  9. import com.lovo.dao.StuDao;  
  10. import com.lovo.databasetest.R;  
  11.   
  12. public class DatabaseTestActivity extends Activity {  
  13.     private TextView show;  
  14.     private StuDao dao;  
  15.   
  16.     @Override  
  17.     protected void onCreate(Bundle savedInstanceState) {  
  18.         super.onCreate(savedInstanceState);  
  19.         setContentView(R.layout.main);  
  20.         show = (TextView) findViewById(R.id.main_tv_show);  
  21.         dao = new StuDao(this);  
  22.     }  
  23.   
  24.     public void click(View v) {  
  25.         switch (v.getId()) {  
  26.   
  27.         case R.id.main_btn_insert:  
  28.             // 添加数据  
  29.             dao.insert("张三"24"男");  
  30.             break;  
  31.         case R.id.main_btn_delete:  
  32.             // 根据指定ID删除数据  
  33.             dao.del(2);  
  34.             break;  
  35.         case R.id.main_btn_update:  
  36.             // 根据指定ID修改数据  
  37.             dao.update("王斌"34"男"1);  
  38.             break;  
  39.         case R.id.main_btn_find:  
  40.             StringBuffer sb = new StringBuffer();  
  41.             // 查询所有数据  
  42.             Cursor cursor = dao.findAll();  
  43.             // 根据指定ID查询数据  
  44.             // Cursor cursor=dao.findById(1);  
  45.             while (cursor.moveToNext()) {  
  46.                 int id = cursor.getInt(cursor.getColumnIndex("_id"));  
  47.                 String name = cursor.getString(cursor.getColumnIndex("s_name"));  
  48.                 String sex = cursor.getString(cursor.getColumnIndex("s_sex"));  
  49.                 int age = cursor.getInt(cursor.getColumnIndex("s_age"));  
  50.                 sb.append(id + " " + name + " " + sex + " " + age + "\n");  
  51.             }  
  52.             show.setText(sb.toString());  
  53.             break;  
  54.   
  55.         }  
  56.     }  
  57.   
  58. }  

布局XML:

[html]  view plain copy
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent"  
  3.     android:layout_height="match_parent"  
  4.     android:orientation="vertical" >  
  5.   
  6.   
  7.     <Button  
  8.         android:id="@+id/main_btn_insert"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:onClick="click"  
  12.         android:text="添加" />  
  13.   
  14.     <Button  
  15.         android:id="@+id/main_btn_delete"  
  16.         android:layout_width="wrap_content"  
  17.         android:layout_height="wrap_content"  
  18.         android:onClick="click"  
  19.         android:text="删除" />  
  20.   
  21.     <Button  
  22.         android:id="@+id/main_btn_update"  
  23.         android:layout_width="wrap_content"  
  24.         android:layout_height="wrap_content"  
  25.         android:onClick="click"  
  26.         android:text="修改" />  
  27.   
  28.     <Button  
  29.         android:id="@+id/main_btn_find"  
  30.         android:layout_width="wrap_content"  
  31.         android:layout_height="wrap_content"  
  32.         android:onClick="click"  
  33.         android:text="查找" />  
  34.   
  35.     <TextView  
  36.         android:id="@+id/main_tv_show"  
  37.         android:layout_width="wrap_content"  
  38.         android:layout_height="wrap_content" />  
  39.   
  40. </LinearLayout>  

SQLiteOpenHelper的子类(DBUtil):

[java]  view plain copy
  1. package com.lovo.dao;  
  2.   
  3. import android.content.Context;  
  4. import android.database.sqlite.SQLiteDatabase;  
  5. import android.database.sqlite.SQLiteDatabase.CursorFactory;  
  6. import android.database.sqlite.SQLiteOpenHelper;  
  7.   
  8. public class DBUtil extends SQLiteOpenHelper {  
  9.     private static DBUtil dbUtil;  
  10.   
  11.     private DBUtil(Context context, String name, CursorFactory factory,  
  12.             int version) {  
  13.         super(context, name, factory, version);  
  14.     }  
  15.   
  16.     public static SQLiteDatabase getInstance(Context context) {  
  17.         if (dbUtil == null) {  
  18.             // 指定数据库名为student,需修改时在此修改;此处使用默认工厂;指定版本为1  
  19.             dbUtil = new DBUtil(context, "student"null1);  
  20.         }  
  21.         return dbUtil.getReadableDatabase();  
  22.     }  
  23.   
  24.     @Override  
  25.     public void onCreate(SQLiteDatabase db) {  
  26.         try {  
  27.             db.execSQL("create table t_stu(_id integer primary key,s_name text,s_age integer,s_sex text)");  
  28.         } catch (Exception e) {  
  29.             e.printStackTrace();  
  30.         }  
  31.     }  
  32.   
  33.     @Override  
  34.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  35.         System.out.println("-----onUpgrade Called-----" + oldVersion + "--->"  
  36.                 + newVersion);  
  37.     }  
  38.   
  39. }  

StuDao类:封装数据操作的方法

[java]  view plain copy
  1. package com.lovo.dao;  
  2.   
  3. import android.content.Context;  
  4. import android.database.Cursor;  
  5. import android.database.sqlite.SQLiteDatabase;  
  6.   
  7. public class StuDao {  
  8.     private SQLiteDatabase db;  
  9.   
  10.     public StuDao(Context context) {  
  11.         db = DBUtil.getInstance(context);  
  12.     }  
  13.   
  14.     /** 
  15.      * 查询所有数据 
  16.      *  
  17.      * @return Cursor 
  18.      */  
  19.     public Cursor findAll() {  
  20.         Cursor cursor = db.rawQuery("select * from t_stu"null);  
  21.         return cursor;  
  22.     }  
  23.   
  24.     /** 
  25.      * 添加数据 
  26.      *  
  27.      * @param name  姓名 
  28.      * @param age  年龄 
  29.      * @param sex  性别 
  30.      */  
  31.     public void insert(String name, int age, String sex) {  
  32.         db.execSQL("insert into t_stu values(null,?,?,?)"new String[] { name,  
  33.                 age + "", sex });  
  34.     }  
  35.   
  36.     /** 
  37.      * 删除数据 
  38.      *  
  39.      * @param id 
  40.      */  
  41.     public void del(int id) {  
  42.         db.execSQL("delete from t_stu where _id=?"new String[] { id + "" });  
  43.     }  
  44.   
  45.     /** 
  46.      * 根据id查询数据 
  47.      *  
  48.      * @param id 
  49.      * @return Cursor 
  50.      */  
  51.     public Cursor findById(int id) {  
  52.         Cursor cursor = db.rawQuery("select * from t_stu where _id=?",  
  53.                 new String[] { id + "" });  
  54.         return cursor;  
  55.     }  
  56.   
  57.     /** 
  58.      * 修改数据 
  59.      *  
  60.      * @param name 姓名 
  61.      * @param age  年龄 
  62.      * @param sex  性别 
  63.      * @param id   id 
  64.      */  
  65.     public void update(String name, int age, String sex, int id) {  
  66.         db.execSQL("update t_stu set s_name=?,s_age=?,s_sex=? where _id=?",  
  67.                 new Object[] { name, age, sex, id });  
  68.     }  
  69. }  





 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值