SQLite實時增刪改查

基礎知識:
先介紹一點兒基礎知識
SQLite的增刪改查以及建立表語句:
1,建立表語句:java

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

2,增長一條數據語句:mysql

<pre name="code" class="java">//若是像這樣一個語句經過加號鏈接起來,必定要注意空格問題,
//insert into 表名 (字段列表)values(?,?) 
 db.execSQL("insert into "+tableName+" (name,age) values(?,?) ",new String[]{name,age});

不然會出現以下問題android

﹕ FATAL EXCEPTION: main
    android.database.sqlite.SQLiteException: near "intoEmployee": syntax error (code 1): , 
        while compiling: insert intoEmployee(name,age) values(?,?)

3,刪除一條數據:sql

//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});

至於要調用那些增刪改查的方法,實質上就是在拼接這些基本語句,只要掌握住這些基本語句,那些方法要傳什麼參數也就很好理解了
上述的語句是根本,掌握了他們就能夠很好的觸類旁通了
好比,咱們通常會調用的數據庫增刪改查方法爲:ide

db.insert(tableName, null, values);//增長一條數據<pre name="code" class="java">db.query(tableName, null, "name=?", new String[]{name}, null, null, null);//查詢一條數據
db.delete(tableName, "name=?", new String[]{name});//刪除一條數據
<pre name="code" class="java">db.update(tableName, values, "name=?", 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, null, versionCode);
    }

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

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //更新數據庫操做
    }
}

以及本身建立的personbean數據:this

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.javacode

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, null, values);
            //若是像這樣一個語句經過加號鏈接起來,必定要注意空格問題,
//            db.execSQL("insert into "+tableName+" (name,age) values(?,?) ",new String[]{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, "name=?", 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, values, "name=?", new String[]{oldName});
//            db.execSQL("update "+tableName+" set name=? , age=? where name=?",new String[]{newName,newAge,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, "name=?", new String[]{name}, null, null, 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, null, null, null, null, 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);
        }
    }
}

至於佈局文件,很簡單,就不往上貼了,但願對你們有所幫助,

相關文章
相關標籤/搜索