android SQLITE的基本使用总结(八)

sharedPreferences只适合存储比较简单的数据和键值对,支持不同的数据类型

文件存储连键值对都没有,不会进行任何格式化处理,存储简单的二进制或者文本数据

sqlite则能处理一些数据量大,并且结构比较复杂的数据

管理sqlite   SQLiteHelper:抽象类,要使用的话就要创建自己的帮助类去继承它,并且重写oncreate和onupgrade,    

还有两个实例方法可以调用:  getreadabledatabase()  getwritabledatabase()  都可以创建或者打开数据库,但是getreadabledatabase可以再数据库不可写入的的时候继续以只读方式打开,但是另一个方法  将会产生异常    

重写构造函数:一般使用简单的参数这个**(context,数据库名字,cursor,版本号)

使用android adb来查看是否创建成功,需要配置adb环境变量 adb的环境变量path D:andriodadt-bundle-windows-x86-20140702adt-bundle-windows-x86-20140702sdkplatform-tools java的环境变量  %JAVA_HOME%in;

创建数据库:

创建数据库
//先定义一个类MyDatabaseHelper
public class MyDatabaseHelper extends SQLiteOpenHelper{
    public static final String CREATE_BOOK="create table Book("+"id integer primary key autoincrement,"+"tuthor text,"+"price real,"+"pages integer,"+"name text)";
    //创建一个新表升级数据库
    public static final String CREATE_CATEGORY="create table Category("+"id integer primary key autoincrement,"+"catagory_name text,"+"categoty_code integer)";
    
    private Context mContext;
    public MyDatabaseHelper(Context context,String name,CursorFactory factory,int version){
        super(context, name, factory, version);
        mContext=context;
    }
    public void onCreate(SQLiteDatabase db){
        db.execSQL(CREATE_BOOK);
        db.execSQL(CREATE_CATEGORY);//新增表category的见表语句
        Toast.makeText(mContext, "Create secceed", Toast.LENGTH_SHORT).show();
    }
    public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){
        switch(oldVersion) {////升级数据库当老版本是1的时候就只创建在版本2中新加的表,直接安装时就两个表一起创建
        case 1:db.execSQL(CREATE_CATEGORY);//这里没有使用break是为了保证在跨程序升级的时候能够全部创建所有升级的数据库
        case 2:sb.execSQL(CREATE_CATEGORY);
        default:
        }
    }

}
//在主函数中进行创建数据库
public class MainActivity extends Activity {
    private MyDatabaseHelper dbHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dbHelper=new MyDatabaseHelper(this,"BoolStore.db",null,2);//此处的数字决定了是否执行更新操作
        Button createDatabase=(Button) findViewById(R.id.create_database);
        createDatabase.setOnClickListener(new OnClickListener(){
            public void onClick(View v){
                dbHelper.getWritableDatabase();//检查是否有库,没有就创建并且电泳oncreate见表,有就不创建
            }
        });
        Button adddata=(Button)findViewById(R.id.adddata);
        adddata.setOnClickListener(new OnClickListener(){
            public void onClick(View v){
                SQLiteDatabase db=dbHelper.getWritableDatabase();//getWritableDatabase会返回一个可以操作的对象
                ContentValues values=new ContentValues();
                values.put("name","The Da vinci code");
                values.put("author","dan brown");
                values.put("pages",450);
                values.put("price",16);
                db.insert("Book",null,values);
                values.clear();
                //开始插入第二条
                values.put("name","the lost symbol");
                ..
                ..
                db.inset("Book",null,values);
                //开始给另一个表插入
                values.put("categoty_code","12465");
                ..
                .
                db.insert("Category",null,values);
                //id我们设为自增长了所以不用单独赋给id
            }
        });
        //更新表中的数据
        Button updatedata=(Button)findViewById(R.id.updatedata);
        updatedata.setOnClickListener(new OnClickListener{    
            public void onClick(View v){
                SQLiteDatabase db=dbHelper.getWritableDatabase();
                ContentValues values=new ContentValues();
                values.put("price",10);
                db.update("Book",values,"name=?",new String[]{"the davinci code"});//这里指定书名为the davinci code 的且在book表中的价格修改为10
                }
        });
        //删除数据
        Button deletedata=(Button)findViewById(R.id.deletedata);
        deletedata.setOnClickListener(new OnClickListener{    
            public void onClick(View v){
                SQLiteDatabase db=dbHelper.getWritableDatabase();
                db.delete("Book","pages>?","new String[]{"500"}")//这里指定删除book中页数大于500的书籍
                }
        });
        Button queryButton=(Button)findViewById(R.id.queruButton);
        queryButton.setOnClickListener(new OnClickListener(){
            public void onClick(View v){
                SQLiteDatabase db=dbHelper.getWritableDatabase();
                Cursor cursor=db.query("Book",null,null,null,null,null,null);//查询完后得到一个Cursor对象,接着调用moveToFirst()遍历
                if(cursor.moveToFirst()){
                    do{
                        String name=cursor.getString(cursor.getColumnIndex("name"));
                        String author=cursor.getString(cursor.getColumnIndex("author"));
                        ..
                    }while(cursor.moveToNext());//取出所有的book中的数据
                }
                cursor.close();
            }
        });
        
    }
}

为了连贯的操作一系列的动作,要么全部完成要么全部不能完成
使用事务:

..
public void onClick(View v){
    SQLiteDatabase db=dbHelper.getWritableDatabase();
    db.beginTransaction();
    try{
        db.delete("Book",null,null);
        if(true){
        throw new NullPointException();//手动抛出异常
        }
        ContentValues values=new ContentValues();
        values.put("name","bookname");
        values.put("author","bookauthor");
        ...
        db.insert("Book",null,values);
        db.setTransactionSuccessful();//事务执行成功
    }catch(Exception e){
    e.printStackTrace();
    }finally{
        db.endTransaction();//结束事务
    }
}
原文地址:https://www.cnblogs.com/zzy-frisrtblog/p/5361694.html