Android中SQLite的使用

來源:互聯網
上載者:User

標籤:pen   抽象   建立   log   ring   help   count()   let   else   

一、如何建立資料庫和表?

     自己的類繼承抽象類別SQLiteOpenHelper。

  (1)修改中的構造方法中的super方法建立資料庫

  (2)第一個抽象方法用於建立表

二、如何進行增刪改查,代碼如下:

public class StudentDao {    private StudentSqliteOpenHelper studentSqliteOpenHelper;    public StudentDao(Context context){        studentSqliteOpenHelper = new StudentSqliteOpenHelper(context);    }    //增    public boolean add(Student student){        SQLiteDatabase db = studentSqliteOpenHelper.getReadableDatabase();        ContentValues values = new ContentValues();        values.put("name",student.name);        values.put("age",student.age);        values.put("school",student.school);        long result = db.insert("student", null, values);        db.close();        if(result != -1){            return true;        }else{            return false;        }    }    //刪    public int del(String name){        SQLiteDatabase db = studentSqliteOpenHelper.getReadableDatabase();        int delLines = db.delete("student", "name = ?", new String[]{name});        db.close();        return delLines;    }    //改    public int update(Student student){        SQLiteDatabase db = studentSqliteOpenHelper.getReadableDatabase();        ContentValues values = new ContentValues();        values.put("name",student.name);        values.put("age",student.age);        values.put("school",student.school);        int result = db.update("student", values, "name = ?", new String[]{student.name});        db.close();        return result;    }    //查    public ArrayList<Student> query(String name){        SQLiteDatabase db = studentSqliteOpenHelper.getReadableDatabase();        Cursor cursor = db.rawQuery("select * from student where name = ?", new String[]{name});        ArrayList<Student> arrayList = new ArrayList<>();        if(cursor != null && cursor.getCount() > 0){            //遍曆cursor            while (cursor.moveToNext()){                Student s = new Student();                s.id = cursor.getLong(0);                s.name = cursor.getString(1);                s.age = cursor.getInt(2);                s.school = cursor.getString(3);                arrayList.add(s);            }        }        db.close();        return arrayList;    }}

 

  

 

Android中SQLite的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.