搭建Android本地数据库(SQLite)的详细讲解

       大家好,今天我给大家整理了一些关于Android本地数据库SQLite搭建的详细步骤!

       SQLite是一款轻型的数据库,它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了。SQLite引擎不是个程序与之通信的独立进程,而是连接到程序中成为它的一个主要部分。所以主要的通信协议是在编程语言内的直接API调用。这在消耗总量、延迟时间和整体简单性上有积极的作用。

        首先,我们先建立一个Constant.java类来存放一些关于数据库的常量如下:

 

package com.example.boybaby.yicetong.SQLiteDatabase;

/**
 * Created by Boy Baby on 2018/3/15.
 */

public class Constant {
    public static final String DATABASE_NAME = "info.db";  // 数据库名称
    public static final int DATABASE_VERSION = 1;          //数据库版本
    public static final String TABLE_NAME = "TH_Data";     //数据库表名
    /**
     *ID、TEMP、HUMIDITY、CO2、LAST_TIME、LAST_TIME 一下是数据库表中的字段
     */
    public static  final String ID = "id";                //id主键
    public static  final String TEMP = "temp";            //温度
    public static final String HUMIDITY = "humidity";     //湿度
    public static final String CO2 = "co2";               //二氧化碳
    public static final String LAST_TIME = "lastUpdateTime";//更新时间
    /**
     *  TP_DATA 第二个表
     */
    public static final String TABLE1_NAME = "TP_DATA";
    public static  final String CITY = "city";
}

        然后,我们创建一个类来写创建数据库的方法类,该类(MySqliteHelper)继承于SQLiteOpenHelper,该类封装了一系列关于数据库的增删改查的方法,如下:

 

package com.example.boybaby.yicetong.SQLiteDatabase;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
 * Created by Boy Baby on 2018/3/14.
 */

public class MySqliteHelper extends SQLiteOpenHelper {
    /**
     *
     * @param context 上下文对象
     * @param name 创建数据库名字
     * @param factory 工厂
     * @param version 版本
     */
    //构造函数
    public MySqliteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }
    public MySqliteHelper(Context context){
        super(context,Constant.DATABASE_NAME,null,Constant.DATABASE_VERSION);
    }
    /*
    创建数据库时使用的函数
     */
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        String sql = "create table "+Constant.TABLE_NAME+"("+
                Constant.ID+" Integer primary key ,"+
                Constant.TEMP+" Integer,"+
                Constant.HUMIDITY+" Integer,"+
                Constant.CO2+" Integer,"+
                Constant.LAST_TIME+" varchar(50))";
        sqLiteDatabase.execSQL(sql);

        String sql1 = "create table "+Constant.TABLE1_NAME+" ("+
                Constant.ID+" Integer primary key ,"+
                Constant.CITY+" varchar(20)) ";
        sqLiteDatabase.execSQL(sql1);
    }
    /**
     *  更新数据库时调用
     * @param sqLiteDatabase
     * @param i
     * @param i1
     */
    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}

数据库建好之后,我们再建立一个DbManger类,是写数据库操作的工具类如下:

 

package com.example.boybaby.yicetong.SQLiteDatabase;

/**
 * Created by Boy Baby on 2018/3/14.
 */

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
/**
 * Created by 11929 on 2018/3/11.
 * 主要对数据库的操作工具类
 */
public class DbManger {

    private static MySqliteHelper helper; //建立一个数据库对象

    /**
     *
     * @param context 本类的上下文对象
     * @return
     */
    public static MySqliteHelper getIntance(Context context){
        if (helper == null){
            helper = new MySqliteHelper(context);
        }
        return helper;
    }
    /**
     * 查找方法
     * 返回的是一个Cursor对象
     * selectionArgs 查询条件占位符
     */
    public static Cursor selectSQL(SQLiteDatabase db, String sql, String[] selectionArgs){
        Cursor cursor = null;
        if (db != null){
            cursor = db.rawQuery(sql,selectionArgs);
        }
        return cursor;
    }
    /**
     * 删改数据库
     * @param db  数据库对象
     * @param sql 删改语句
     */
    public static void execSQL(SQLiteDatabase db, String sql){
        if (db!=null) {
            if (sql != null && !"".equals(sql)) {
                db.execSQL(sql);
            }
        }
    }

    /**
     * 将Curcor对象转化成list集合
     * @param cursor 游标
     * @return 集合对象
     */
    public static ArrayList<TH_Data> cursorToList(Cursor cursor){
        ArrayList<TH_Data> list = new ArrayList<>();
        while (cursor.moveToNext()){   //判断游标是否有下一个字段
            //getColumnIndext作用是返回给定字符串的下标(指的是int类型)
            int columnIndex = cursor.getColumnIndex(Constant.ID);
            //通过下标找到指定value
            int id = cursor.getInt(columnIndex);  // 获取id
            int temp = cursor.getInt( cursor.getColumnIndex(Constant.TEMP)); //获取温度
             int humidity = cursor.getInt(cursor.getColumnIndex(Constant.HUMIDITY)); //获取湿度
             int co2 = cursor.getInt(cursor.getColumnIndex(Constant.CO2)); //获取二氧化碳
             String time = cursor.getString(cursor.getColumnIndex(com.example.boybaby.yicetong.SQLiteDatabase.Constant.LAST_TIME)); //获取时间
             TH_Data th_data = new TH_Data(id,temp,humidity,co2,time);
            list.add(th_data);
        }
        return list;
    }
    
    public static ArrayList<TP_Data> cursor1ToList(Cursor cursor){
        ArrayList<TP_Data> list = new ArrayList<TP_Data>();
        while (cursor.moveToNext()) {
            int id = cursor.getInt(cursor.getColumnIndex(Constant.ID));
            String city = cursor.getString(cursor.getColumnIndex(Constant.CITY));
            TP_Data tp_data = new TP_Data(id, city);
            list.add(tp_data);
        }
        return list;
    }
}

再建立一个存放数据的类:

 

package com.example.boybaby.yicetong.SQLiteDatabase;

/**
 * Created by Boy Baby on 2018/3/15.
 */

public class TH_Data {
    private int ID;
    private int TEMP;
    private int HUMIDITY;
    private int CO2;
    private String time;
    public String toTemp(){
        return this.getTEMP()+" ";
    }
    public String toHumidity(){
        return this.getHUMIDITY()+" ";
    }
    public String toCo2(){
        return this.getCO2()+"";
    }
    public TH_Data(int ID, int TEMP, int HUMIDITY, int CO2, String TIME) {
        this.ID = ID;
        this.TEMP = TEMP;
        this.HUMIDITY = HUMIDITY;
        this.CO2 = CO2;
        this.time = TIME;

    }
    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public int getID() {
        return ID;
    }

    public void setID(int ID) {
        this.ID = ID;
    }

    public int getTEMP() {
        return TEMP;
    }

    public void setTEMP(int TEMP) {
        this.TEMP = TEMP;
    }

    public int getHUMIDITY() {
        return HUMIDITY;
    }

    public void setHUMIDITY(int HUMIDITY) {
        this.HUMIDITY = HUMIDITY;
    }

    public int getCO2() {
        return CO2;
    }

    public void setCO2(int CO2) {
        this.CO2 = CO2;
    }
}

在MainActivity.java中进行数据的插入,如下:

第一:创建数据库:

 

/*
点击按钮创建数据库
 */
 public void createDB(){
     SQLiteDatabase db =  helper.getWritableDatabase();  //创建数据库
     db.close();
 }

       第二:查询数据库:

 

//查询数据库
SQLiteDatabase db = helper.getWritableDatabase();
String selectSql = "select * from "+Constant.TABLE_NAME;
Cursor cursor = DbManger.selectSQL(db,selectSql,null);//查询结果用cursor类型数据存储
if(cursor.getCount()==0){
    i=1;
}else{
    i=cursor.getCount()+1;
}
//获取到数据插入数据库
String sql = "insert into " + Constant.TABLE_NAME +" values ("+i+","+temp_value+","+humidity_value+","+co2_value+",'"+time_temp+"')";
DbManger.execSQL(db,sql);//执行语句
db.close();

 

注意:查询完数据库要及时关闭!

 

db.close();//关闭数据库

 

 

 

 

  • 4
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值