数据库—单例设计,基本操作

来源:互联网 发布:缎面连衣裙淘宝 编辑:程序博客网 时间:2024/06/07 00:57

数据库帮助类 SQLiteOpenHelper 建表后。

这时通过设计一个数据库操作类,同时根据表内容创建表对应的实体类,能更加清晰安全的操作数据库。

下面详细讲解一下数据库操作类的创建。

数据库操作类用单例模式创建,这样保证只有一个数据库操作类的实例。

(每次返回数据库操作类时都已经连接数据库了只需要调用数据库操作类里自定义操作方法即可对数据库操作)


单例模式做法

1.私有构造函数

2.提供静态方法创造一个该类的对象

3.返回该类对象。

这里我们用懒汉式单例创建。同时加上同步锁 ,这样可以保证线程安全。


在构造函数中通过数据库帮助类打开一个数据库。这样在整个数据库操作类里就可以通过这个打开的数据库引用对该数据库进行增删改查。

面向对象思想体现:

增删改查,通过传入的实体类,获取实体类对象里面的信息进而对数据库操作。


public class CoolWeatherdb {    public static final String DB_NAME="cool_weather";    public static final int VERSON=1;    private static CoolWeatherdb coolWeatherdb;    private CoolWeatherdbHelper coolWeatherdbHelper;    //打开的数据库对象    private   SQLiteDatabase db;     //私有化构造方法    单例使这个类只有一个对象    private CoolWeatherdb(Context context) {         coolWeatherdbHelper =new CoolWeatherdbHelper(context,DB_NAME,null,VERSON);         db=  coolWeatherdbHelper.getWritableDatabase();    }    public  synchronized static CoolWeatherdb getInstance(Context context){        if(coolWeatherdb==null)        {            coolWeatherdb=new CoolWeatherdb(context);        }        return  coolWeatherdb;    }    //接下来写一些对数据库操作的方法(XXX为实体类)。


数据库操作方法:

插入写法:

   db.execSQL("insert into 表名(列名1,列名2,列名3) values(" + "'"+值1如果是汉字是单引号+"'"+ "," + 值2用逗号隔开 + "," +值3+ ") ");       

这种插入的写法基本可以满足需要。另外一种结合select 是复制用的

查询写法:

1.

返回所有列的游标结果集合

 Cursor cursor= db.rawQuery("select * from 表名 where province_id=?",new String[]{String.valueOf(?的值)});//注意后面数组是为了填写前面通配符的值!!        


2.

当查询完毕后为了验证是结果集合里是否真的有内容可以打log进行一波判断

Log.d("验证","返回行和列的个数"+cursor.getCount()+cursor.getColumnCount());

3.

通过游标集合把内容拿出来:

List<City> lsc =new ArrayList<City>();结果集一般用list 集合保存起来。 if(cursor.moveToFirst()){            do{                City city=new City();                city.setCity_name(cursor.getString(cursor.getColumnIndex("city_name")));//千万注意不要把列名写错了 多一个空格也是不行的 如果没有该列则返回的是-1;//如果错误提示返回-1 游标初始化不正确就要查看是不是列名写错。
//通过列名获取值得方式更加清晰                city.setCity_code(cursor.getInt(cursor.getColumnIndex("city_code")));                city.setProvince_code(province_id);                              lsc.add(city);                           }while(cursor.moveToNext());        }if(cursor!=null){     cursor.close();}


4

删除:

    db.execSQL("delete from tablename where column="+"\""+xxxx+"\"");


5

更改:

UPDATE 表名 set 列名称 =新值 WHERE 列名称 =某值

  db.execSQL("update blackman set mode="+"\""+mode+"\""+"where PhoneNumber="+"\""+number+"\"");




0 0