Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> Android之SqlLite數據庫使用,androidsqllite

Android之SqlLite數據庫使用,androidsqllite

編輯:關於android開發

Android之SqlLite數據庫使用,androidsqllite


  public class MyDatabaseHelper extends SQLiteOpenHelper { private static final String db_name = "SQLite_db.db";//數據文件的名字 private static int NUMBER = 1;//當前數據庫版本,用於升級 private static final String table_name = "students";//表名 private static String sql = null;//sql語句 public MyDatabaseHelper(Context context) { super(context, db_name, null, NUMBER);//數據庫文件保存在當前應用所在包名:<包>/database/ } @Override public void onCreate(SQLiteDatabase db) { sql = "CREATE TABLE " + table_name + " (" + "id INTEGER PRIMARY KEY ," + "name VARCHAR(50) NOT NULL)";//創建數據庫的SQL語句 db.execSQL(sql);//執行SQL語句 } /** * 當數據庫進行升級是調用,這裡通過NUMBER值來進行判斷,數據庫是否升級 */ public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { //第一種寫法 sql = "ALTER TABLE " + table_name + " ADD sex VARCHAR(2) NULL"; Log.i("sql", sql); db.execSQL(sql); //第二種寫法 //db.execSQL("ALTER TABLE students ADD sex VARCHAR(10) NULL"); } }

  下面我們在主Activity中創建這個類,然後進行數據的生成:

public class Activityone extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_one);
        
        //創建SqlLite數據庫
        SQLiteOpenHelper helper = new MyDatabaseHelper(this);
        helper.getWritableDatabase();
    }
}

  到這裡我們關於SQLite的創建就為大家分享完畢,需要提示的就是onUpgrade()方法,這個方法一般不執行,當我們的數據庫版本發生變化時,才會被執行。


  下面我們來一起學習一下如何在Android中來使用SQLite數據庫,來完成對數據的增、刪、改、查、統計。

  我們通過創建一個管理學生信息的數據庫來完成對SQLite功能的介紹展示,首先為了方便對學生類進行管理,我們先創建一個學生類:

public class tab_students {
    
    public Integer id;//學生Id
    public String name;//學生姓名
    public String password;//學生密碼
    public String school;//學生學校
    
    public tab_students(){
        
    }
    
    public tab_students(int _id,String _name,String _password){
        id=_id;
        name=_name;
        password=_password;
    }
    
    public Integer getId() {
        return id;
    }
    
    public void setId(int id) {
        this.id = id;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String _name) {
        name = _name;
    }
    
    public String getPassword() {
        return password;
    }
    
    public void setPassword(String _password) {
        password = _password;
    }
    
    public String getSchool() {
        return school;
    }
    
    public void setSchool(String _school) {
        school = _school;
    }

    @Override
    public String toString() {
        return "id:"+this.getId()+"  name:"+this.getName()+"  password:"+this.getPassword();
    }
    
}

  有了學生類,下面我們創建數據庫配置文件:

public class MyTabOpen extends SQLiteOpenHelper{
    
    private static final String db_sql = "SQLiter.db"; 
    private static int NUMBER = 1;
    private static final String tab_name = "students";
    private static String sql = null;
    
    public MyTabOpen(Context context) {
        super(context, db_sql, null, NUMBER);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        sql = "CREATE TABLE " + tab_name + " (" + 
                "id            INTEGER         PRIMARY KEY ," + 
                "name        VARCHAR(20)        NOT NULL ," +
                "password   VARCHAR(20)     NOT NULL)";
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        
        //在更新數據庫時,因原先數據庫表中已有數據,所以新增加的列屬性只能設置為“可以為空”
        db.execSQL("ALTER TABLE students ADD school VARCHAR(10) NULL");
        
    }

}

  對於這個文件,大家有什麼疑問請看上面的SQLite數據庫創建講解。

  這裡我們的主Activity的代碼如下,對於主Activity的布局文件,就不在粘代碼了,布局文件全是Button按鈕:

public class Activityone extends Activity {
    
    private static tab_students stu = null;
    private static tab_service ser = null;
    private static int conn = 1;

    private TextView mytext = null;
    private Button mybutton1 = null;//添加數據
    private Button mybutton2 = null;//刪除數據
    private Button mybutton3 = null;//修改數據
    private Button mybutton4 = null;//查詢數據
    private Button mybutton5 = null;//分頁獲取數據
    private Button mybutton6 = null;//獲取數據總數
    private Button mybutton7 = null;//普通頁面跳轉
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_one);
        mytext = (TextView)findViewById(R.id.textview);
        mytext.setText("增刪改查序"+"("+"sql語句"+")");
        
        mybutton1 = (Button)findViewById(R.id.button1);
        mybutton2 = (Button)findViewById(R.id.button2);
        mybutton3 = (Button)findViewById(R.id.button3);
        mybutton4 = (Button)findViewById(R.id.button4);
        mybutton5 = (Button)findViewById(R.id.button5);
        mybutton6 = (Button)findViewById(R.id.button6);
        mybutton7 = (Button)findViewById(R.id.button7);
        
        mybutton1.setOnClickListener(new mybuttonlistener());
        mybutton2.setOnClickListener(new mybuttonlistener());
        mybutton3.setOnClickListener(new mybuttonlistener());
        mybutton4.setOnClickListener(new mybuttonlistener());
        mybutton5.setOnClickListener(new mybuttonlistener());
        mybutton6.setOnClickListener(new mybuttonlistener());
        mybutton7.setOnClickListener(new mybuttonlistener());
        
    }
    
    class mybuttonlistener implements OnClickListener{

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.button1://添加數據
                ser =new tab_service(getApplicationContext());                
                stu = new tab_students(conn++,"小米","abc123");
                ser.save(stu);
                break;

            case R.id.button2://刪除數據
                ser =new tab_service(getApplicationContext());                
                ser.del(1);
                break;
                
            case R.id.button3://修改數據
                ser =new tab_service(getApplicationContext());                
                stu = new tab_students(1,"HTC","acm123");
                ser.update(stu);
                break;
                
            case R.id.button4://查詢數據
                ser =new tab_service(getApplicationContext());                
                stu=ser.find(1);
                System.out.println(stu.toString());                
                break;
                
            case R.id.button5://分頁獲取數據
                ser =new tab_service(getApplicationContext());
                List<tab_students> list = ser.getScrollDate(0,5);
                for(tab_students stu : list){
                    System.out.println(stu.toString());    
                }
                break;
                
            case R.id.button6://獲取數據總數
                long number = 0;
                ser =new tab_service(getApplicationContext());                
                number=ser.gettab();
                System.out.println("數據庫中共有:"+number+"條記錄.");                
                break;

            default:
                Activityone.this.startActivity(new Intent(Activityone.this,Activitytwo.class));//普通跳轉
                break;
            }
        }
    }
}

  大家可能已經看到了,這裡我們對SQLite的操作,都是通過tab_service.java類完成了,下面就為大家揭曉如何對SQLite進行操作:

public class tab_service {
    
    private MyTabOpen mytabopen = null;
    private static SQLiteDatabase db = null;
    private static String sql = null;
    private static final String tab_name = "students";
    
    public tab_service(Context context) {
        this.mytabopen = new MyTabOpen(context);//獲得數據庫操作實例
    }

    //添加數據
    public void save(tab_students students){
        db = mytabopen.getWritableDatabase();
        sql = "insert into "+tab_name+"(id,name,password) values(?,?,?)";
        db.execSQL(sql, new Object[]{students.getId(),students.getName(),students.getPassword()});
        db.close();            //為了提高性能sqliter數據庫可以不關閉
    }
    
    //刪除數據
    public void del(Integer id){
        db = mytabopen.getWritableDatabase();
        sql = "delete from "+tab_name+" where id = ?";
        db.execSQL(sql, new Object[]{id});
        db.close();
    }
    
    //更新數據
    public void update(tab_students students){
        db = mytabopen.getWritableDatabase();
        sql = "update "+tab_name+" set name=?,password=? where id=?";
        db.execSQL(sql, new Object[]{students.getName(), students.getPassword(), students.getId()});
        db.close();
    }
    
    //查詢數據
    public tab_students find(Integer id){
        
        //getReadableDatabase()與getWritableDatabase()通過查看源代碼知道,getReadableDatabase()方法在磁盤空間滿的時候,仍能返回數據庫操作實例,不過此時的實例只能用於讀不能寫
        db = mytabopen.getReadableDatabase();
        sql = "select * from "+tab_name+ " where id=?";
        Cursor cur = db.rawQuery(sql, new String[]{id.toString()});
        if(cur.moveToFirst()){
            String name = cur.getString(cur.getColumnIndex("name"));
            String password = cur.getString(cur.getColumnIndex("password"));
            return new tab_students(id,name,password);
        }
        cur.close();
        db.close();
        return null;
    }
    
    //分頁獲取數據
    public List<tab_students> getScrollDate(int again,int last){
        
        List<tab_students> list = new ArrayList<tab_students>();
        db = mytabopen.getReadableDatabase();
        sql = "select * from "+tab_name+ "limit ?,? order by id asc";//根據查詢結果的id對數據進行升序排列
        //sql = "select * from " +tab_name+ " limit ?,?";
        Cursor cur = db.rawQuery(sql, new String[]{String.valueOf(again), String.valueOf(last)});
        while (cur.moveToNext()) {
            int id = cur.getInt(cur.getColumnIndex("id"));
            String name = cur.getString(cur.getColumnIndex("name"));
            String password = cur.getString(cur.getColumnIndex("password"));
            
            tab_students stu = new tab_students(id, name, password);
            list.add(stu);
        }
        cur.close();
        db.close();
        return list;
    }

    //獲取數據總數目
    public long gettab(){
        db = mytabopen.getReadableDatabase();
        sql = "select count(*) from "+tab_name;
        Cursor cur = db.rawQuery(sql, null);
        cur.moveToFirst();
        long result = cur.getLong(0);
        return result;
    }
}

  是不是感覺和我們的SQL數據庫操作一樣,sql語句沒有什麼區別,是的,他們完全一致。沒學過數據庫的小朋友是不是已經抓狂啦,不要擔心,Android工程師想到了你們,Android為我們封裝好了一套對SQLite數據庫進行操作的規范,下面我們就一起來學習一下,如何通過Android提供的規范晚場上面的操作。

  這裡我們只需要修改一下,我們上面對數據庫操作的類:

public class tab_service_two {
    
    private MyTabOpen mytabopen = null;
    private static SQLiteDatabase db = null;
    private static final String tab_name = "students";
    
    public tab_service_two(Context context) {
        this.mytabopen = new MyTabOpen(context);//獲得數據庫操作實例
    }

    //添加數據
    public void save(tab_students students){
        db = mytabopen.getWritableDatabase();         
        ContentValues values = new ContentValues();
        values.put("id", students.getId());
        values.put("name", students.getName());
        values.put("password", students.getPassword());
        db.insert(tab_name, null, values);
        db.close();
    }
    
    //刪除數據
    public void del(Integer id){
        db = mytabopen.getWritableDatabase();
        db.delete(tab_name, "id=?", new String[]{id.toString()});
        db.close();
    }
    
    //修改數據
    public void update(tab_students students){
        db = mytabopen.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("name", students.getName());
        values.put("password", students.getPassword());
        db.update(tab_name, values, "id=?", new String[]{students.getId().toString()});
        db.close();
    }
    
    //查詢數據
    public tab_students find(Integer id){
        //getReadableDatabase()與getWritableDatabase()通過查看源代碼知道,getReadableDatabase()方法在磁盤空間滿的時候,仍能返回數據庫操作實例,不過此時的實例只能用於讀不能寫
        db = mytabopen.getReadableDatabase();
        //當要查詢數據庫表中的所以信息時,第二個參數可以使用設置為空來代替數組
        Cursor cur = db.query(tab_name, new String[]{"name","password"}, "id=?", new String[]{id.toString()}, null, null, null);
        
        if(cur.moveToFirst()){
            String name = cur.getString(cur.getColumnIndex("name"));
            String password = cur.getString(cur.getColumnIndex("password"));
            return new tab_students(id,name,password);
        }
        cur.close();
        db.close();
        return null;
    }
    
    //分頁獲取數據
    public List<tab_students> getScrollDate(int again,int last){
        List<tab_students> list = new ArrayList<tab_students>();
        db = mytabopen.getReadableDatabase();
        
        Cursor cur = db.query(tab_name, null, null, null, null, null, "id asc", again+","+last);
        while (cur.moveToNext()) {
            int id = cur.getInt(cur.getColumnIndex("id"));
            String name = cur.getString(cur.getColumnIndex("name"));
            String password = cur.getString(cur.getColumnIndex("password"));
            
            tab_students stu = new tab_students(id, name, password);
            list.add(stu);
        }
        cur.close();
        db.close();
        return list;
    }

    //獲取數據總數
    public long gettab(){
        db = mytabopen.getReadableDatabase();
        Cursor cur = db.query(tab_name, new String[]{"count(*)"}, null, null, null, null, null);
        cur.moveToFirst();
        long result = cur.getLong(0);
        return result;
    }
}

  好了關於SQLite在Android平台的使用,就為大家介紹完畢,內容很簡單,沒有太大的難度,相信小伙伴一定能理解。新手學習,高手交流。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved