SQLite实时增删改查

前端之家收集整理的这篇文章主要介绍了SQLite实时增删改查前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

基础知识:
先介绍一点儿基础知识
sqlite的增删改查以及创建表语句:
1,创建表语句:

//CREATE TABLE+表名(字段列表)
<pre name="code" class="java">db.execsql("CREATE TABLE Employee(EmployeeId integer primary key autoincrement,name varchar(20),age varchar(20))");

2,增加一条数据语句:

<pre name="code" class="java">//如果像这样一个语句通过加号连接起来,一定要注意空格问题,
//insert into 表名 (字段列表)values(?,?) 
 db.execsql("insert into "+tableName+" (name,age) values(?,?) ",new String[]{name,age});

否则会出现如下问题

﹕ FATAL EXCEPTION: main
    android.database.sqlite.sqliteException: near "intoEmployee": Syntax error (code 1):,while compiling: insert intoEmployee(name,?)

3,删除一条数据:

//delete from 表名 where 字段=?
db.execsql("delete from "+tableName+" where name=?",new String[]{name});

4,查询一条数据:

//select * from 表名 where 字段=?
db.rawQuery("select * from "+tableName+" where name = ?",new String[]{name});

5,修改一条数据

//update 表名 set 字段=?,字段=? where name = ?,以上代码出现的数组所传的参数与问号相对应,很容易理解
db.execsql("update "+tableName+" set name=?,age=? where name=?",new String[]{newName,newAge,oldName});

至于要调用那些增删改查的方法,实质上就是在拼接这些基本语句,只要掌握住这些基本语句,那些方法要传什么参数也就很好理解了
上述的语句是根本,掌握了他们就可以很好的举一反三了
比如,我们一般会调用数据库增删改查方法为:

db.insert(tableName,null,values);//增加一条数据<pre name="code" class="java">db.query(tableName,"name=?",new String[]{name},null);//查询一条数据
db.delete(tableName,new String[]{name});//删除一条数据
<pre name="code" class="java">db.update(tableName,values,new String[]{oldName});//更新一条数据

实例展示:
先看一下我的实例运行效果吧,实现了增删改查并且实时刷新的功能,以及item 的点击事件

item点击时,弹出所选中的姓名和年龄:

查询一条语句,并且显示出来:

如果所查询的语句不存在,则在显示搜索结果的地方显示搜索到结果
增加一条数据和删除一条数据以及更新一条语句都可以进行实时更新,不需要手动刷新
实例源码:
只给效果图不给源码的不是好博主,上源码:
首先
MysqLiteHelper.java文件

public class MysqLiteHelper extends sqliteOpenHelper {


    private static String versionName = "Employee";
    private static int versionCode = 1;



    public MysqLiteHelper(Context context) {
        super(context,versionName,versionCode);
    }

    @Override
    public void onCreate(sqliteDatabase db) {
        db.execsql("CREATE TABLE Employee (EmployeeId integer primary key autoincrement,age varchar(20))");
    }

    @Override
    public void onUpgrade(sqliteDatabase db,int oldVersion,int newVersion) {
        //更新数据库操作
    }
}

以及自己创建的personbean数据:

public class PersonBean {
    private String name;
    private String age;

    public PersonBean() {
    }

    public PersonBean(String name,String age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}

对personbean集成的增删改查类
Personsqlite.java

public class Personsqlite {

    private sqliteOpenHelper mDBOpenHelper;
    private sqliteDatabase db;
    private Context mContext;
    private String tableName;

    public Personsqlite(Context context,String tableName) {
        this.mContext = context;
        mDBOpenHelper = new MysqLiteHelper(context);
        this.tableName = tableName;

    }

    /**
     * 增加一条数据,
     *
     * @param name
     * @param age
     * @return 当i为-1时则表示添加失败
     */
    public long insert(String name,String age) {
        long i = -1;
        db = mDBOpenHelper.getWritableDatabase();
        if (db.isOpen()) {
            ContentValues values = new ContentValues();
            values.put("name",name);
            values.put("age",age);
            i = db.insert(tableName,values);
            //如果像这样一个语句通过加号连接起来,一定要注意空格问题,
//            db.execsql("insert into "+tableName+" (name,age});
            db.close();
        }
        return i;
    }

    /**
     * 删除一条数据
     *
     * @param name
     * @return
     */
    public boolean delete(String name) {
        db = mDBOpenHelper.getWritableDatabase();
        if (db.isOpen()) {
//            db.execsql("delete from "+tableName+" where name =?",new String[]{name});
            db.delete(tableName,new String[]{name});
            db.close();
            return true;
        }
        return false;
    }


    /**
     * 更新操作,
     *
     * @param oldName
     * @param newName
     * @param newAge
     * @return
     */
    public int update(String oldName,String newName,String newAge) {
        db = mDBOpenHelper.getWritableDatabase();
        int i = -1;
        if (db.isOpen()) {
            ContentValues values = new ContentValues();
            values.put("name",newName);
            values.put("age",newAge);
            i = db.update(tableName,new String[]{oldName});
//            db.execsql("update "+tableName+" set name=?,oldName});
            db.close();
        }
        return i;
    }

    /**
     * 查询数据的操作
     *
     * @param name
     * @return 返回查询到的数据
     */
    public PersonBean query(String name) {
        db = mDBOpenHelper.getReadableDatabase();
        PersonBean personBean = null;
        if (db.isOpen()) {
//            Cursor cursor = db.rawQuery("select * from "+tableName+" where name = ?",new String[]{name});
            Cursor cursor = db.query(tableName,null);
            if (cursor.moveToFirst()) {
                personBean = new PersonBean();
                int nameIndex = cursor.getColumnIndex("name");
                int ageIndex = cursor.getColumnIndex("age");
                String nameStr = cursor.getString(nameIndex);
                String ageStr = cursor.getString(ageIndex);
                personBean.setAge(ageStr);
                personBean.setName(nameStr);
                cursor.close();
            }
            db.close();
        }
        return personBean;
    }


    /**
     * 查询数据库中的所有数据
     *
     * @return
     */
    public List<PersonBean> queryAll() {
        db = mDBOpenHelper.getReadableDatabase();
        List<PersonBean> personBeanList = null;
        if (db.isOpen()) {
            personBeanList = new ArrayList<>();
            Cursor cursor = db.query(tableName,null);
            while (cursor.moveToNext()) {
                PersonBean personBean = new PersonBean();
                int nameIndex = cursor.getColumnIndex("name");
                int ageIndex = cursor.getColumnIndex("age");
                String nameStr = cursor.getString(nameIndex);
                String ageStr = cursor.getString(ageIndex);
                personBean.setName(nameStr);
                personBean.setAge(ageStr);
                personBeanList.add(personBean);
            }
            cursor.close();
            db.close();
        }
        return personBeanList;
    }
}

接下来就是主程序了:

public class MysqLActivity extends Activity implements View.OnClickListener {

    private RecyclerView mRecyclerView;
    private MysqLRecyclerViewAdapter mAdapter;
    private static List<PersonBean> personBeanList = new ArrayList<>();
    private Personsqlite personsqlite;




    private EditText mSearchEt;
    private TextView mSearchTv;

    private EditText msqlDataEt;
    private TextView mInsert;
    private TextView mDelete;
    private TextView mUpdate;

    private EditText mSearchResultEt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_MysqL);


        mSearchEt = (EditText) findViewById(R.id.search_et);
        mSearchTv = (TextView) findViewById(R.id.search_tv);

        mRecyclerView = (RecyclerView) findViewById(R.id.rl_sql_data);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        personsqlite = new Personsqlite(this,"Employee");




        msqlDataEt = (EditText) findViewById(R.id.sql_data_et);
        mInsert = (TextView) findViewById(R.id.insert);
        mDelete = (TextView) findViewById(R.id.delete);
        mUpdate = (TextView) findViewById(R.id.update);

        mSearchResultEt = (EditText) findViewById(R.id.search_data_result_et);
        setData();
        mRecyclerView.setAdapter(mAdapter);
        setOnClickListener(mSearchTv,mInsert,mDelete,mUpdate);

    }

    private void setData(){
        personBeanList = personsqlite.queryAll();
        mAdapter = new MysqLRecyclerViewAdapter(MysqLActivity.this);
        mAdapter.resetData(personBeanList);
    }




    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    public void onClick(View v) {
        PersonBean personBean = null;
        String mSearchStr = mSearchEt.getText().toString().trim();
        String msqlDataStr = msqlDataEt.getText().toString().trim();
        int i = -1;
        switch (v.getId()) {
            case R.id.search_tv:
                personBean = personsqlite.query(mSearchStr);
                if (personBean != null) {
                    mSearchResultEt.setText("搜索结果为:姓名为:"+personBean.getName()+"年龄为:"+personBean.getAge());
                }else {
                    mSearchResultEt.setText("未能搜索到相关信息");
                }
                break;
            case R.id.insert:
                if (personsqlite.query(msqlDataStr)!=null){
                    Toast.makeText(getApplicationContext(),"禁止重复添加数据",Toast.LENGTH_LONG).show();
                    return;
                }
                personsqlite.insert(msqlDataStr,"100");
                break;
            case R.id.delete:
                personBean = personsqlite.query(msqlDataStr);
                if (null == personBean ){
                    Toast.makeText(getApplicationContext(),"要删除的数据不存在",Toast.LENGTH_LONG).show();
                    return;
                }
                personsqlite.delete(msqlDataStr);
                break;
            case R.id.update:
                personBean = personsqlite.query(msqlDataStr);
                if (null == personBean){
                    Toast.makeText(getApplicationContext(),"要更新的数据不存在",Toast.LENGTH_LONG).show();
                    return;
                }
                personsqlite.update(msqlDataStr,"更新后的姓名","更新后的年龄");
                break;
            default:
                break;
        }

        mSearchEt.setText("");
        msqlDataEt.setText("");
        personBeanList = personsqlite.queryAll();
        mAdapter.resetData(personBeanList);

    }

    private void setOnClickListener(View... views) {
        for (View view : views) {
            if (view != null) {
                view.setOnClickListener(MysqLActivity.this);
            }
        }
    }
}

因为用到的是Recyclerview,所以还需要自定义适配器adapter

public class MysqLRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements View.OnClickListener{

    private Context context;
    private List<PersonBean> personBeanList;

    public MysqLRecyclerViewAdapter(Context context) {
        this.context = context;
        personBeanList = new ArrayList<>();
    }

//每次数据改变时调用方法,可以实现实时刷新效果
    public void resetData(List<PersonBean> list){
        personBeanList.clear();
        personBeanList.addAll(list);
        notifyDataSetChanged();
    }
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
        View view = View.inflate(context,R.layout.list_item_layout,null);
        return new ContentViewHolder(view);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder,final int position) {
        if (holder instanceof ContentViewHolder){
            ContentViewHolder contentViewHolder = (ContentViewHolder) holder;
            contentViewHolder.mName.setText("姓名:"+personBeanList.get(position).getName());
            contentViewHolder.mAge.setText("年龄:"+personBeanList.get(position).getAge());
            contentViewHolder.container.setTag(R.id.tag_age,personBeanList.get(position).getAge());
            contentViewHolder.container.setTag(R.id.tag_name,personBeanList.get(position).getName());
            contentViewHolder.container.setOnClickListener(this);
        }
    }

    @Override
    public int getItemCount() {
        return personBeanList.size();
    }

    @Override
    public void onClick(View v) {
        String name = (String) v.getTag(R.id.tag_name);
        String age = (String) v.getTag(R.id.tag_age);
        Toast.makeText(context,"姓名:"+name+",年龄"+age,Toast.LENGTH_LONG).show();
    }

    private class ContentViewHolder extends RecyclerView.ViewHolder {

        TextView mName;
        TextView mAge;
        View container;
        public ContentViewHolder(View itemView) {
            super(itemView);
            container = itemView;
            mName = (TextView) itemView.findViewById(R.id.name);
            mAge = (TextView) itemView.findViewById(R.id.age);
        }
    }
}

至于布局文件,很简单,就不往上贴了,希望对大家有所帮助,

猜你在找的Sqlite相关文章