在前文中总结了SQLite数据库的基本用法,本文中将使用SQLiteOpenHelper和单例模式来操作数据库。SQLiteOpenHelper是Android提供的一个管理数据库的工具类,可以用于管理数据库的创建和版本更新。一般的用法是创建它的子类,并扩展它的onCreate()和onUpgrade方法。
SQLiteOpenHelper包含如下方法:
同上文一样,数据仍是手动写死的,实际情况应该根据业务需求从界面或其他地方获取,实例代码如下,关键是后面两个类:
Activity:
- package com.lovo.activity;
- import android.app.Activity;
- import android.database.Cursor;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.TextView;
- import com.lovo.dao.StuDao;
- import com.lovo.databasetest.R;
- public class DatabaseTestActivity extends Activity {
- private TextView show;
- private StuDao dao;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- show = (TextView) findViewById(R.id.main_tv_show);
- dao = new StuDao(this);
- }
- public void click(View v) {
- switch (v.getId()) {
- case R.id.main_btn_insert:
- // 添加数据
- dao.insert("张三", 24, "男");
- break;
- case R.id.main_btn_delete:
- // 根据指定ID删除数据
- dao.del(2);
- break;
- case R.id.main_btn_update:
- // 根据指定ID修改数据
- dao.update("王斌", 34, "男", 1);
- break;
- case R.id.main_btn_find:
- StringBuffer sb = new StringBuffer();
- // 查询所有数据
- Cursor cursor = dao.findAll();
- // 根据指定ID查询数据
- // Cursor cursor=dao.findById(1);
- while (cursor.moveToNext()) {
- int id = cursor.getInt(cursor.getColumnIndex("_id"));
- String name = cursor.getString(cursor.getColumnIndex("s_name"));
- String sex = cursor.getString(cursor.getColumnIndex("s_sex"));
- int age = cursor.getInt(cursor.getColumnIndex("s_age"));
- sb.append(id + " " + name + " " + sex + " " + age + "\n");
- }
- show.setText(sb.toString());
- break;
- }
- }
- }
布局XML:
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
- <Button
- android:id="@+id/main_btn_insert"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:onClick="click"
- android:text="添加" />
- <Button
- android:id="@+id/main_btn_delete"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:onClick="click"
- android:text="删除" />
- <Button
- android:id="@+id/main_btn_update"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:onClick="click"
- android:text="修改" />
- <Button
- android:id="@+id/main_btn_find"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:onClick="click"
- android:text="查找" />
- <TextView
- android:id="@+id/main_tv_show"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- </LinearLayout>
SQLiteOpenHelper的子类(DBUtil):
- package com.lovo.dao;
- import android.content.Context;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteDatabase.CursorFactory;
- import android.database.sqlite.SQLiteOpenHelper;
- public class DBUtil extends SQLiteOpenHelper {
- private static DBUtil dbUtil;
- private DBUtil(Context context, String name, CursorFactory factory,
- int version) {
- super(context, name, factory, version);
- }
- public static SQLiteDatabase getInstance(Context context) {
- if (dbUtil == null) {
- // 指定数据库名为student,需修改时在此修改;此处使用默认工厂;指定版本为1
- dbUtil = new DBUtil(context, "student", null, 1);
- }
- return dbUtil.getReadableDatabase();
- }
- @Override
- public void onCreate(SQLiteDatabase db) {
- try {
- db.execSQL("create table t_stu(_id integer primary key,s_name text,s_age integer,s_sex text)");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- System.out.println("-----onUpgrade Called-----" + oldVersion + "--->"
- + newVersion);
- }
- }
StuDao类:封装数据操作的方法
- package com.lovo.dao;
- import android.content.Context;
- import android.database.Cursor;
- import android.database.sqlite.SQLiteDatabase;
- public class StuDao {
- private SQLiteDatabase db;
- public StuDao(Context context) {
- db = DBUtil.getInstance(context);
- }
- /**
- * 查询所有数据
- *
- * @return Cursor
- */
- public Cursor findAll() {
- Cursor cursor = db.rawQuery("select * from t_stu", null);
- return cursor;
- }
- /**
- * 添加数据
- *
- * @param name 姓名
- * @param age 年龄
- * @param sex 性别
- */
- public void insert(String name, int age, String sex) {
- db.execSQL("insert into t_stu values(null,?,?,?)", new String[] { name,
- age + "", sex });
- }
- /**
- * 删除数据
- *
- * @param id
- */
- public void del(int id) {
- db.execSQL("delete from t_stu where _id=?", new String[] { id + "" });
- }
- /**
- * 根据id查询数据
- *
- * @param id
- * @return Cursor
- */
- public Cursor findById(int id) {
- Cursor cursor = db.rawQuery("select * from t_stu where _id=?",
- new String[] { id + "" });
- return cursor;
- }
- /**
- * 修改数据
- *
- * @param name 姓名
- * @param age 年龄
- * @param sex 性别
- * @param id id
- */
- public void update(String name, int age, String sex, int id) {
- db.execSQL("update t_stu set s_name=?,s_age=?,s_sex=? where _id=?",
- new Object[] { name, age, sex, id });
- }
- }