Android 操作自带的Sqlite数据库(增、删、改、查)

时间:2021-10-01 20:15:06

1、先创建一个Product类 Product.java

变量如下:

    int id;
    String code;
    String name;
    int qty;

2、创建一个DBHelper类 DBHelper.java

DBHelper类继承于SQLiteOpenHelper ,创建一个test.db的数据库,创建一张product表,并对product表进行增删改查操作。

import java.util.ArrayList;
import java.util.HashMap;

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

public class DBHelper extends SQLiteOpenHelper {

    public final static String DB_NAME = "test.db";
    public final static int VERSION = 1;
    private static DBHelper instance = null;
    private SQLiteDatabase db;

    public static DBHelper getInstance(Context context) {
        if (instance == null) {
            instance = new DBHelper(context);
        }
        return instance;
    }

    private void openDatabase() {
        if (db == null) {
            db = getWritableDatabase();
        }
    }

    private DBHelper(Context context) {
        super(context, DB_NAME, null, VERSION);
    }

    /** 第一次安装程序后创建数据库 */
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table product (_id integer primary key autoincrement,code text,name text,qty Integer )");
    }

    /** 版本升级时,先删除原有的数据库,再重新创建数据库 */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("drop table if exist product");
        onCreate(db);
    }

    /** 添加一条数据 */
    public long saveLamp(Product pro) {
        ContentValues value = new ContentValues();
        value.put("code", pro.getCode());
        value.put("name", pro.getName());
        value.put("qty", pro.getQty());
        return db.insert("product", null, value);
    }

    /** 根据id删除数据 */
    public int deleteLamp(int id) {
        return db.delete("product", "_id=?", new String[] { String.valueOf(id) });
    }

    /** 根据id更新数据 */
    public int updateLamp(Product pro, int id) {
        ContentValues value = new ContentValues();
        value.put("code", pro.getCode());
        value.put("name", pro.getName());
        value.put("qty", pro.getQty());
        return db.update("product", value, "_id=?", new String[] { String.valueOf(id) });
    }

    /** 查询所有数据 */
    public ArrayList<HashMap<String, Object>> getLampList() {
        openDatabase();
        Cursor cursor = db.query("product", null, null, null, null, null, null);
        ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
        while (cursor.moveToNext()) {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("id", cursor.getInt(cursor.getColumnIndex("_id")));
            map.put("code", cursor.getString(cursor.getColumnIndex("code")));
            map.put("name", cursor.getString(cursor.getColumnIndex("name")));
            map.put("qty", cursor.getString(cursor.getColumnIndex("qty")));
            list.add(map);
        }
        return list;
    }

    /** 根据编码查询数据 */
    public Product getALamp(String code) {
        openDatabase();
        Cursor cursor = db.query("product", null, "code=?", new String[] { code }, null, null, null);
        Product pro = new Product();
        while (cursor.moveToNext()) {
            pro.setId(cursor.getInt(cursor.getColumnIndex("_id")));
            pro.setCode(cursor.getString(cursor.getColumnIndex("code")));
            pro.setName(cursor.getString(cursor.getColumnIndex("name")));
            pro.setQty(cursor.getInt(cursor.getColumnIndex("qty")));
        }
        return pro;
    }

    /** 查询有多少条记录 */
    public int getLampCount() {
        openDatabase();
        Cursor cursor = db.query("product", null, null, null, null, null, null);
        return cursor.getCount();
    }

}

3、测试数据 MainActivity .java

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        exec();// 测试数据

    }

    private void exec() {
        /** 添加数据 */
        Product product1 = new Product("pingguo", "红富士苹果", 100);
        long sucess1 = DBHelper.getInstance(MainActivity.this).saveLamp(product1);
        Log.d("test", "sucess=" + sucess1);
        if (sucess1 > 0) {
            // "添加成功!"
        } else {
            // "添加失败,请重新操作!"
        }

        /** 修改数据 */
        Product product2 = new Product("pingguo", "红富士苹果", 100);
        int updateId = 5;
        int sucess2 = DBHelper.getInstance(MainActivity.this).updateLamp(product2, updateId);
        if (sucess2 > 0) {
            // "修改成功!"
        } else {
            // "修改失败,请重新操作!"
        }

        /** 删除数据 */
        int deleteId = 5;
        int sucess = DBHelper.getInstance(MainActivity.this).deleteLamp(deleteId);
        if (sucess > 0) {
            // "删除成功!"
        } else {
            // "删除失败!"
        }

        /** 获取表记录数 */
        int count = DBHelper.getInstance(MainActivity.this).getLampCount();

        /** 获取所有数据 */
        ArrayList<HashMap<String, Object>> data = DBHelper.getInstance(MainActivity.this).getLampList();

    }
}