Android开发之sqlite数据库的应用

第一步先定义自己需要的表结构。

第二步定义helper方法,建表,定义更新表的内容

第三步定义数据对象,set、get

第四步定义数据库的适配器,定义增删查改方法,方便SQLitedatabase对象直接调用
套路:
1.创建SQLiteDatabase对象,并调用getWritableDatabase 或getReadableDatabase方法
SQLiteDatabase db=dbhelper.getWritableDatabase();
2.增: 创建ContentValues对象values,往values里放值,让后调用db.insert()方法
删:找到删除条件,调用db.delete()方法
改: 创建ContentValues对象values,往values里放值,同时确认要修改的条件
查:确认要查的条件,调用db.query()方法获取内容,并赋值给一个Cursor对象。 若只有一个查询结果,直接复制给数据对象,若有多行值,创建ArrayList对象,放入循环放入其中。
3.调用db.close() (若创建了Cursor对象c,需要需关闭,c.close())

第五步 调用适配器方法
1.创建一个DatabaseAdapter对象,并实例化dbAdapter=new DatabaseAdapter(this);
2.调用方法:
增:创建一个数据对象,并赋值,然后调用dbAdapter.add()
删:调用dbAdapter.delete()
改:创建新的数据对象,赋值,然后调用dbAdapter.updata();
查:调用查方法,并赋值Dog dog=dbAdapter.findById(1);若有多行值,则创建ArrayList对象,循环赋值

代码如下:

package com.Cactus.sqlitetest;

import android.provider.BaseColumns;
//第一步先定义自己需要的表结构
public final class PetMetaData 
{
    private PetMetaData(){}
    public static abstract class DogTable implements BaseColumns
    {
        public static final String TABLE_NAME = "dog";
        public static final String NAME = "name";
        public static final String AGE = "age";
    }
}
package com.Cactus.sqlitetest;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
//第二步定义helper方法,建表,定义更新表的内容

public class DatabaseHelper extends SQLiteOpenHelper{
    private static final String DB_NAME="pet.db";
    private static final int VERSION=1;
    private static final String CREATE_TABLE_DOG="CREATE TABLE dog(_id INTEGER PRIMARY KEY AUTOINCREMENT"+
    ",name TEXT,age INTEGER)";
    private static final String DROP_TABLE_DOG="DROP TABLE IF EXISTS dog";
    //定义方法
    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, VERSION);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL(CREATE_TABLE_DOG);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL(DROP_TABLE_DOG);
        db.execSQL(CREATE_TABLE_DOG);

    }

}
package com.Cactus.sqlitetest;
//第三步定义数据对象,set、get
public class Dog {
    private int id;
    private String name;
    private int age;
    public Dog()
    {

    }
    public Dog(int id,String name,int age)
    {
        this.id=id;
        this.name=name;
        this.age=age;
    }
    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Dog [id=" + id + ", name=" + name + ", age=" + age + "]";
    }   

}
package com.Cactus.sqlitetest;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
//第四步定义数据库的适配器,定义增删查改方法,方便SQLitedatabase对象直接调用

public class DatabaseAdapter {
    private DatabaseHelper dbhelper;
    public DatabaseAdapter(Context context) {
        dbhelper=new DatabaseHelper(context);
    }
    //套路:
//          1.创建SQLiteDatabase对象,并调用getWritableDatabase 或getReadableDatabase方法
    //              SQLiteDatabase db=dbhelper.getWritableDatabase();
    //      2.增: 创建ContentValues对象values,往values里放值,让后调用db.insert()方法
    //            删:找到删除条件,调用db.delete()方法
        //    改:  创建ContentValues对象values,往values里放值,同时确认要修改的条件
    //        查:确认要查的条件,调用db.query()方法获取内容,并赋值给一个Cursor对象。 若只有一个查询结果,
    //          直接复制给数据对象,若有多行值,创建ArrayList对象,放入循环放入其中。
    //      3.调用db.close()  (若创建了Cursor对象c,需要需关闭,c.close())
    public void add(Dog dog)
    {
        SQLiteDatabase db=dbhelper.getWritableDatabase();
        ContentValues values=new ContentValues();
        values.put(PetMetaData.DogTable.NAME, dog.getName());
        values.put(PetMetaData.DogTable.AGE, dog.getAge());
        db.insert(PetMetaData.DogTable.TABLE_NAME, null, values);
        db.close();
    }
    public void delete(int id)
    {
        SQLiteDatabase db=dbhelper.getWritableDatabase();
        String whereClause=PetMetaData.DogTable._ID+"+?";
        String[] whereArgs={String.valueOf(id)};
        db.delete(PetMetaData.DogTable.TABLE_NAME, whereClause, whereArgs);
        db.close();
    }
    public void updata(Dog dog)
    {
        SQLiteDatabase db=dbhelper.getWritableDatabase();
        ContentValues values=new ContentValues();
        values.put(PetMetaData.DogTable.NAME, dog.getName());
        values.put(PetMetaData.DogTable.AGE, dog.getAge());
        String whereClause=PetMetaData.DogTable._ID+"+?";
        String[] whereArgs={String.valueOf(dog.getId())};
        db.update(PetMetaData.DogTable.TABLE_NAME, values, whereClause, whereArgs);
        db.close();

    }
    public Dog findById(int id)
    {
        SQLiteDatabase db=dbhelper.getReadableDatabase();
        String[] columns={PetMetaData.DogTable._ID,PetMetaData.DogTable.NAME,PetMetaData.DogTable.AGE};
        Cursor c=db.query(true, PetMetaData.DogTable.TABLE_NAME, columns, PetMetaData.DogTable._ID+"=?", new String[]{String.valueOf(id)}, null, null, null, null, null);
        Dog dog=null;
        if(c.moveToNext())
        {
            dog=new Dog();
            dog.setId(c.getInt(c.getColumnIndexOrThrow(PetMetaData.DogTable._ID)));
            dog.setAge(c.getInt(c.getColumnIndexOrThrow(PetMetaData.DogTable.AGE)));
            dog.setName(c.getString(c.getColumnIndexOrThrow(PetMetaData.DogTable.NAME)));
        }
        c.close();
        db.close();
        return dog;
    }
    public ArrayList findAll()
    {
        SQLiteDatabase db=dbhelper.getReadableDatabase();
        String[] columns={PetMetaData.DogTable._ID,PetMetaData.DogTable.NAME,PetMetaData.DogTable.AGE};
        Cursor c=db.query(true, PetMetaData.DogTable.TABLE_NAME, columns, null, null, null, null, null, null, null);
        ArrayList dogs=new ArrayList();
        Dog dog=null;
        while(c.moveToNext())
        {
            dog=new Dog();
            dog.setId(c.getInt(c.getColumnIndexOrThrow(PetMetaData.DogTable._ID)));
            dog.setAge(c.getInt(c.getColumnIndexOrThrow(PetMetaData.DogTable.AGE)));
            dog.setName(c.getString(c.getColumnIndexOrThrow(PetMetaData.DogTable.NAME)));
            dogs.add(dog);
        }
        c.close();
        db.close();
        return dogs;
    }

}
package com.Cactus.sqlitetest;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
//第五步 调用适配器方法:
// 1.创建一个DatabaseAdapter对象,并实例化dbAdapter=new DatabaseAdapter(this);
// 2.调用方法:
    //  增:创建一个数据对象,并赋值,然后调用dbAdapter.add();
//      删:调用dbAdapter.delete()
//      改:创建新的数据对象,赋值,然后调用dbAdapter.updata();
//      查:调用查方法,并赋值Dog dog=dbAdapter.findById(1);若有多行值,则创建ArrayList对象,循环赋值

public class MainActivity extends Activity {
    private DatabaseAdapter dbAdapter;
    private Button add,delete,updata,findById,findAll;
    private TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dbAdapter=new DatabaseAdapter(this);
        add=(Button)findViewById(R.id.add);
        delete=(Button)findViewById(R.id.delete);
        updata=(Button)findViewById(R.id.updata);
        findById=(Button)findViewById(R.id.findById);
        findAll=(Button)findViewById(R.id.findAll);
        text=(TextView)findViewById(R.id.textView1);

        addListener addlistener=new addListener();
        add.setOnClickListener(addlistener);
        updataListener updatalistener =new updataListener();
        updata.setOnClickListener(updatalistener);
        deleteListener deletelistener=new deleteListener();
        delete.setOnClickListener(deletelistener);
        findByIdListener findbyidlistener =new findByIdListener();
        findById.setOnClickListener(findbyidlistener);
        findAllListener findalllistener=new findAllListener();
        findAll.setOnClickListener(findalllistener);


    }
    class addListener implements OnClickListener
    {

        @Override
        public void onClick(View v) {
            Dog dog=new Dog("beibei", 5);
            dbAdapter.add(dog);
        }

    }
    class deleteListener implements OnClickListener
    {

        @Override
        public void onClick(View v) {
            dbAdapter.delete(1);
        }

    }
    class updataListener implements OnClickListener
    {

        @Override
        public void onClick(View v) {
            Dog dog=new Dog("jingjing", 5);
            dbAdapter.updata(dog);
        }

    }
    class findByIdListener implements OnClickListener
    {

        @Override
        public void onClick(View v) {
            Dog dog=dbAdapter.findById(1);
            System.out.print(dog);
            Log.v(dog.getName(), "------------------------");
        }

    }
    class findAllListener implements OnClickListener
    {

        @Override
        public void onClick(View v) {
            ArrayList dogs=dbAdapter.findAll();
            int size=dogs.size();
            for(int i=0;i//              System.out.print(dogs.get(i));
                Log.v(dogs.get(i).getName(), "---------------------");
            }
        }

    }

}

你可能感兴趣的:(android开发)