数据库
首页 > 数据库> > Android Sqlite

Android Sqlite

作者:互联网

DBHelper  

package com.example.ex_2;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DbHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "test.db";  //数据库名字
    private static final int DATABASE_VERSION = 1 ;         //数据库版本号
    private static final String TABLE_ = "remark";
    private static final String TAG = "mydebug";

    //创建 students 表的 sql 语句
    private static final String CReate_SQL = "create table if not exists "+
            TABLE_ + "("
            + "id integer primary key autoincrement,"
            + "title varchar(100) not null,"
            + "content varchar(1000),"
            + "creat_time datetime not null,"
            + "noti_time datetime not null"
            + ");";
    public DbHelper(Context context){
        super(context, "test.db", null, 1);
    }

    /*创建数据库
    * id是主键自增*/
    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d(TAG, "onCreate: ");
        db.execSQL(CReate_SQL);
    }
    /**
     * 当检测与前一次创建数据库版本不一样时,先删除表再创建新表
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_);
        onCreate(db);
    }

    /**
     * 变更列名
     * @param db
     * @param oldColumn
     * @param newColumn
     * @param typeColumn
     */
    public void updateColumn(SQLiteDatabase db, String oldColumn, String newColumn, String typeColumn){
        try{
            db.execSQL("ALTER TABLE " +
                    TABLE_ + " CHANGE " +
                    oldColumn + " "+ newColumn +
                    " " + typeColumn
            );
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
View Code

增删改查

package com.example.ex_2;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.Cursor;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class Sql {
    private static String TAG = "mydegbug";
    private DbHelper dbHelper;
    private SQLiteDatabase db;
    public Sql(Context context)
    {
        Log.d(TAG, "Sql: init");
        System.out.println("创建数据库");
        /* 初始化并创建数据库 */
        dbHelper = new DbHelper(context);
//        dbHelper.getWritableDatabase();
    }

    //增
    /*
    * remark 要存入数据库的实体类
     */
    public void add(BeanRemark remark)
    {
        dbHelper.updateColumn(db, "crea_time", "creat_time", "datetime");
        Log.d(TAG, "add: zeng");
        db = dbHelper.getWritableDatabase();    //调用SQLiteHelper.OnCreat()

        //用容器存储
        ContentValues values = new ContentValues();
        values.put("title", remark.getTitle());
        values.put("content", remark.getContent());
        values.put("noti_time", remark.getNoti_time());
        values.put("creat_time", remark.getCreat_time());
        long result = db.insert("remark", null, values);

        db.close();
        Log.d(TAG, "add: " + result);
    }

    //删
    //传入要删除对象的id  空的就全删
    public void delete(List<String> remarksId) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        Log.d(TAG, "delete: " + remarksId);
        int result = 0;
        if(!remarksId.isEmpty()) {
            for(String Id : remarksId)
                result = db.delete("remark", "id = ?", new String[]{Id});
        }
        else
            result = db.delete("remark", null,null);
        db.close();

        Log.d(TAG, "delete: res = " + result);

    }

    public void update(BeanRemark remark) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        ContentValues values = new ContentValues();
        if(remark.getTitle() != null)   values.put("title", remark.getTitle());
        if(remark.getContent() != null)   values.put("content", remark.getContent());
        if(remark.getNoti_time() != null)   values.put("noti_time", remark.getNoti_time());
        if(remark.getCreat_time() != null)values.put("creat_time", remark.getCreat_time());

        int result = db.update("remark", values, "id=?", new String[] {""+remark.getId()});
        db.close();

        Log.d(TAG, "update: res = " +  result);
    }

    public List<BeanRemark> find(BeanRemark remark) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        List<String> selections = new ArrayList();
        List<String> vals = new ArrayList();

        //判断 remark 里的哪些量不为空 以此来作为where 条件
        if(remark.getId() != -1)
        {
            selections.add("id = ?");
            vals.add((String) (""+remark.getId()));
        }
        if(remark.getTitle() != null)
        {
            selections.add("title = ?");
            vals.add((String) remark.getTitle());
        }
        if(remark.getContent() != null)
        {
            selections.add("content = ?");
            vals.add((String) remark.getContent());
        }
        if(remark.getNoti_time() != null)
        {
            selections.add("noti_time = ?");
            vals.add((String) remark.getNoti_time());
        }
        if(remark.getCreat_time() != null)
        {
            selections.add("Creat_time = ?");
            vals.add((String) remark.getCreat_time());
        }
        String selection = new String();
        for(int i = 0; i < selections.size(); i++)
        {
            if(i != 0) selection += "and";
            selection += selections.get(i);
        }
        if(selections.size() > 1)
        {
            selection += "and";
            selection += selections.get(selections.size()-1);
        }
        Log.d(TAG, "find: " + selection);
        Log.d(TAG, "find2: " + vals.toArray(new String[vals.size()]));
        Cursor cursor = db.query("remark", null, selection, vals.toArray(new String[vals.size()]), null, null, null);
        List<BeanRemark> remarks = new ArrayList<BeanRemark>();
        while (cursor.moveToNext()) {
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            String title = cursor.getString(cursor.getColumnIndex("title"));
            String content = cursor.getString(cursor.getColumnIndex("content"));
            String noti_time = cursor.getString(cursor.getColumnIndex("noti_time"));
            String creat_time = cursor.getString(cursor.getColumnIndex("creat_time"));

            remarks.add(new BeanRemark(id, title, creat_time, noti_time, content));
        }

        db.close();
        return remarks;
    }

    public List<BeanRemark> findAll()
    {
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        Cursor cursor = db.query("remark", null, null, null, null, null,null);
        List<BeanRemark> remarks = new ArrayList<BeanRemark>();
        BeanRemark remark = null;
        while (cursor.moveToNext()) {
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            String title = cursor.getString(cursor.getColumnIndex("title"));
            String content = cursor.getString(cursor.getColumnIndex("content"));
            String noti_time = cursor.getString(cursor.getColumnIndex("noti_time"));
            String creat_time = cursor.getString(cursor.getColumnIndex("creat_time"));

            remarks.add(new BeanRemark(id, title, creat_time, noti_time, content));
        }

        db.close();
        return remarks;
    }

}
View Code

使用

package com.example.ex_2;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.List;


public class Test extends AppCompatActivity {
    private static String TAG = "mydebug";
    private Sql sql;
    private Button btn1,btn2,btn3,btn4;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        sql = new Sql(this);
        Log.d(TAG, "onCreate: " + new BeanRemark());
        Log.d(TAG, "onCreate: " + sql);
        btn1 = findViewById(R.id.zeng);
        btn1.setOnClickListener(new mClick());
        btn2 = findViewById(R.id.shan);
        btn2.setOnClickListener(new mClick());
        btn3 = findViewById(R.id.gai);
        btn3.setOnClickListener(new mClick());
        btn4 = findViewById(R.id.cha);
        btn4.setOnClickListener(new mClick());
    }

    class mClick implements OnClickListener
    {
        @Override
        public void onClick(View arg)
        {
            switch (arg.getId())
            {
                case R.id.zeng:
                    sql.add(new BeanRemark("wang", Time.CurTime(), "2019-12-20 16:32:00","sds"));
                    sql.add(new BeanRemark("wang", Time.CurTime(), "2019-12-20 16:32:00","sss"));
                    sql.add(new BeanRemark("li", Time.CurTime(), "2019-12-20 16:32:00","sds"));

                    Log.d(TAG, "onClick: zeng");
                    break;
                case R.id.shan:
                    Log.d(TAG, "onClick: shan");
                    List<BeanRemark> list4 = sql.find(new BeanRemark(null, null, null, "sds"));
                    List<String> lisId = new ArrayList();
                    for(BeanRemark item : list4)
                        lisId.add(""+item.getId());
                    sql.delete(lisId);
                    break;
                case R.id.gai:
                    Log.d(TAG, "onClick: gai");
                    sql.update(new BeanRemark(2,null,null,null,"你是傻逼"));
                    break;
                case R.id.cha:
                    Log.d(TAG, "onClick: cha");
                    List<BeanRemark> list = sql.findAll();
                    Log.d(TAG, "onClick: " + list + "\n");
                    List<BeanRemark> list2 = sql.find(new BeanRemark(null, null, null, "sds"));
                    Log.d(TAG, "onClick: " + list2);
                    List<BeanRemark> list3 = sql.find(new BeanRemark(2,null,null,null,null));
                    Log.d(TAG, "onClick: find 2 : " + list3);
                    break;
            }
        }
    }
}
View Code

实体类

package com.example.ex_2;

public class BeanRemark {
    private int id = -1;
    private String title;
    private String creat_time;
    private String noti_time;
    private String content;

    public BeanRemark() {
    }

    public BeanRemark(int id) {
        this.id = id;
    }

    public BeanRemark(String title, String creat_time, String noti_time, String content) {
        this.title = title;
        this.creat_time = creat_time;
        this.noti_time = noti_time;
        this.content = content;
    }

    public BeanRemark(int id, String title, String creat_time, String noti_time, String content) {
        this.id = id;
        this.title = title;
        this.creat_time = creat_time;
        this.noti_time = noti_time;
        this.content = content;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getCreat_time() {
        return creat_time;
    }

    public void setCreat_time(String creat_time) {
        this.creat_time = creat_time;
    }

    public String getNoti_time() {
        return noti_time;
    }

    public void setNoti_time(String noti_time) {
        this.noti_time = noti_time;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    @Override
    public String toString() {
        return "BeanRemark{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", creat_time='" + creat_time + '\'' +
                ", noti_time='" + noti_time + '\'' +
                ", content='" + content + '\'' +
                '}';
    }
}
View Code

标签:remark,String,Sqlite,public,time,Android,null,id
来源: https://www.cnblogs.com/zcfh/p/12076706.html