Android-Sqlite數據庫的操作


Sqlite數據庫的簡單操作:

設置增刪改查的按鈕,xml界面布局設置

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_marginTop="10dp"
    tools:context="com.example.yb.myapplication.DataBaseOperateActivity">
    
    <Button
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/bt_add"
        android:text="增加"/>
    <Button
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/bt_queryAll"
        android:text="查找"/>
    <Button
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/bt_update"
        android:text="修改/更新"/>
    <Button
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/bt_delete"
        android:text="刪除"/>
    
    <ListView
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:id="@+id/lv_stuInfo"></ListView>

</LinearLayout>

  

使用數據庫存儲的步驟:

1新建數據庫:

1.1.創建一個數據庫幫助類MySqliteOpenHelper繼承SqliteOpenHelper,需要添加一個構造方法,實現兩個方法oncreate ,onupgrade
構造方法中的參數介紹:

//context :上下文 ,name:數據庫文件的名稱、 factory:用來創建cursor對象,默認為null 。version:數據庫的版本號,從1開始,如果發生改變,onUpgrade方法將會調用,4.0之后只能升不能將   . super(context, "info.db", null,1);


1.2.復寫oncreate和onupgrdate方法:
oncreate方法是數據庫第一次創建的時候會被調用; 特別適合做表結構的初始化,需要執行sql語句;SQLiteDatabase db可以用來執行sql語句

//onUpgrade數據庫版本號發生改變時才會執行; 特別適合做表結構的修改

public class MySqliteOpenHelper extends SQLiteOpenHelper {

    public MySqliteOpenHelper(Context context) {
        //factory用來創建cursor對象,默認是null
        //super(context, name, factory, version);
        super(context, "info.db", null, 1);
    }

    //第一次的創建的 時候被調用,
    @Override
    public void onCreate(SQLiteDatabase db) {
        //通過SQLiteDatabase執行創建一個sql語句
        db.execSQL("create table info(_id integer primary key autoincrement,name varchar(20),phone varchar(11))");
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    }
}

2:新建一個Bean包,有一個數據的封裝StuInfoBean,新建一個StuInfoBean類

package com.example.yb.Bean;

/**
 * Created by yb on 2016/12/12.
 */
public class StuInfoBean {

    public  String  id;
    public  String  name;
    public String phone;
}

 

3.新建一個包,創建一個數據操作類StuInfoDao,Dao層是對數據進行增刪改查操作

public class StuInfoDao {

    //數據庫幫助類對象
    private MySqliteOpenHelper mySqliteOpenHelper;

    //構造函數
    public StuInfoDao(Context context) {
        mySqliteOpenHelper = new MySqliteOpenHelper(context);
    }

    public boolean add(StuInfoBean stubean) {
        //創建數據庫
        SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();

        //方法一:執行sql語句
        //db.execSQL("insert into info(name,phone) values(?,?);",new Object[]{stubean.name,stubean.phone});

        //方法二
        ContentValues values = new ContentValues();//用map封裝的對象,存放值
        values.put("name", stubean.name);
        values.put("phone", stubean.phone);

    //table: 表名 , nullColumnHack:可以為空,標示添加一個空行, values:數據一行的值 , 返回值:代表添加這個新行的Id ,-1代表添加失敗
long result = db.insert("info", null, values); //返回值是新增的行的id, 失敗是-1 //關閉數據庫對象 db.close(); if (result != -1) { //添加成功 return true; } else { return false; } } public int del(String name) { //創建數據庫,調用getReadableDatabase方法,來初始化數據庫的創建 SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase(); //執行sql語句 //db.execSQL("delete from info where name=?;",new Object[]{name}); //table :表名, whereClause: 刪除條件, whereArgs:條件的占位符的參數 ; 返回值:成功刪除多少行 int result = db.delete("info", "name=?", new String[]{name}); //關閉數據庫對象 db.close(); return result; } public int update(StuInfoBean stubean) { //創建數據庫 SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase(); //執行sql語句 //db.execSQL("update info set phone=? where name=?;", new Object[]{stubean.phone, stubean.name}); ContentValues values = new ContentValues();//是用map封裝的對象,用來存放值 values.put("phone", stubean.phone);

    //table:表名, values:更新的值, whereClause:更新的條件, whereArgs:更新條件的占位符的值,返回值:成功修改多少行

int result = db.update("info", values, "name=?", new String[]{stubean.name});//name=? where的條件
        //關閉數據庫對象
        db.close();
        return result;//返回成功的行數
    }

    public ArrayList<StuInfoBean> query(String name) {
        ArrayList<StuInfoBean> list = new ArrayList<StuInfoBean>();
        //創建數據庫
        SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();

        //執行sql語句,返回一個cursor對象,游標對象
        //Cursor cursor = db.rawQuery("select _id,name,phone from info where name=?", new String[]{name});

      //table:表名, columns:查詢的列名,如果null代表查詢所有列; selection:查詢條件, selectionArgs:條件占位符的參數值,
      //groupBy:按什么字段分組, having:分組的條件, orderBy:按什么字段排序

        Cursor cursor = db.query("info", new String[]{"_id", "name", "phone"}, "name=?", new String[]{name}, null, null, "_id desc");

        if (cursor != null && cursor.getCount() > 0) {
            //循環遍歷結果,獲取每一行的 值
            while (cursor.moveToNext()) {
                StuInfoBean stubean = new StuInfoBean();
                stubean.id = cursor.getInt(0) + "";
                stubean.name = cursor.getString(1);
                stubean.phone = cursor.getString(2);
                list.add(stubean);
            }
            cursor.close();    //關閉結果集
        }
        //關閉數據庫對象
        db.close();
        return list;
    }
}

 

2.Activity里面創建這個幫助類的一個對象,調用getReadableDatabase()方法,會幫助我們創建打開一個數據庫

MySqliteOpenHelper sqlhelper=new MySqliteOpenHelper();
SQLiteDatabase db=sqlhelper.getReadDatabase();

/**
 * 數據庫的操作,增刪改查
 */
public class DataBaseOperateActivity extends AppCompatActivity implements View.OnClickListener {
    private Context mcontext;
    private ListView lv_stuInfo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_base_operate);

        mcontext = this;
        //創建一個數據庫幫助類對象
        MySqliteOpenHelper mySqliteOpenHelper = new MySqliteOpenHelper(mcontext);

        //創建數據庫
        SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();

        findViewById(R.id.bt_add).setOnClickListener(this);
        findViewById(R.id.bt_delete).setOnClickListener(this);
        findViewById(R.id.bt_update).setOnClickListener(this);
        findViewById(R.id.bt_queryAll).setOnClickListener(this);

         lv_stuInfo = (ListView) findViewById(R.id.lv_stuInfo);
    }

    @Override
    public void onClick(View view) {
        StuInfoDao studao = new StuInfoDao(mcontext);
        switch (view.getId()) {
            case R.id.bt_add:
                StuInfoBean stubean=new StuInfoBean();
                stubean.name="aaa";
                stubean.phone="111";
                boolean result = studao.add(stubean);
                if(result){
                    Toast.makeText(mcontext,"添加成功",0).show();
                }else {
                    Toast.makeText(mcontext,"添加失敗",0).show();
                }
                break;
            case R.id.bt_delete:
                int del = studao.del("aaa");
                Toast.makeText(mcontext,"成功刪除了"+del+"",0).show();
                break;
            case R.id.bt_update:
                StuInfoBean bean1=new StuInfoBean();
                bean1.name="aaa";
                bean1.phone="112";
                int update = studao.update(bean1);
                Toast.makeText(mcontext,"成功修改了"+update+"",0).show();
                break;
            case R.id.bt_queryAll:
                //獲取數據
                ArrayList<StuInfoBean> arraylist = studao.query("aaa");
               //封裝QueryAdapter,
                QueryAdapter queryAdapter = new QueryAdapter(mcontext,arraylist);
                //將adapter設置給listview(lv_stuInfo);
                lv_stuInfo.setAdapter(queryAdapter);
                break;
        }

    }
}

 

幫助類對象中的getWritableDatabase 和 getReadableDatabase都可以幫助我們獲取一個數據庫操作對象SqliteDatabase.

 

注意:這里面設計到查詢數據時要展示數據在Listview上,新建一個Adapter包,專門寫adapter的,新建一個QueryAdapter類繼承BaseAdapter,

adapter的基本操作是:

public class QueryAdapter extends BaseAdapter{

    private  Context mcontext;
    private  ArrayList<StuInfoBean> arraylist;

    public QueryAdapter(Context mcontext, ArrayList<StuInfoBean> arraylist) {
        this.mcontext=mcontext;
        this.arraylist=arraylist;
    }

    @Override
    public int getCount() {
        return arraylist.size();
    }

    @Override
    public Object getItem(int i) {
        return arraylist.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view1, ViewGroup viewGroup) {

        //1復用Convertview
        View view=null;
        if(view1!=null){
            view=view1;
        }else{
            view = View.inflate(mcontext, R.layout.item_database_layout, null);

        }
        //2找到控件,view用inflate轉為View對象

        TextView item_tv_id = (TextView) view.findViewById(R.id.item_tv_id);
        TextView item_tv_name = (TextView) view.findViewById(R.id.item_tv_name);
        TextView item_tv_phone = (TextView) view.findViewById(R.id.item_tv_phone);

        //3找到內容,list.get(position);
        StuInfoBean stuInfoBean = arraylist.get(i);

        //4控件設置內容setText
        item_tv_id.setText(stuInfoBean.id);
        item_tv_name.setText(stuInfoBean.name);
        item_tv_phone.setText(stuInfoBean.phone);

        return  view;
    }
}

  1.布局寫listview 

  2.找到listview 

  3.封裝新聞數據到list集合中 ,目的是為adapter提供數據展示。 

  4.封裝一個Adapter類繼承BaseAdatper,寫一個構造方法接受list集合數據,復寫四個方法
    a.創建一個構造方法  
    b.封裝getCount方法  
    c.getView方法: 
      1.復用convertview,模板代碼,如果不都能空,需要將一個布局文件轉換為view對象作為getview的返回對象。
      view = View.inflater(Context context, int resuorceId,ViewGroup root)
      2.找到view上的這些子控件,目的是將list集合中的bean數據一一對應設置給這些子控件

      3.從list集合中獲取postion條目上要顯示的數據Bean

      4.將獲取的bean中的數據設置給這些子控件
    d.getItem方法:將list集合中指定postion上的bean對象返回
    e.getItemId,直接返回postion

  5.創建一個封裝的Adapter對象,設置給listview

上面的代碼是第4步

 

最后界面展示

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM