1、创建SQliteOpenHeplper子类。
2、建立数据库和表结构如下:版本号从1开始。底层以String类型存放
public class LocationInfosDBHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME="gpsinfos.db"; private static final int VERSION=1; public LocationInfosDBHelper(Context context ) { super(context, <span style="color:#ff6666;">DATABASE_NAME</span>, null,<span style="color:#ff0000;"> VERSION</span>); // TODO Auto-generated constructor stub } @Override public void <span style="color:#ff6666;">onCreate</span>(SQLiteDatabase db) { db.execSQL("CREATE TABLE gpsinfos(_id integer primary key autoincrement,longitude TEXT,latitude TEXT, height TEXT)"); } @Override public void<span style="color:#ff6666;"> onUpgrade</span>(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("drop table gpsinfos " ); onCreate(db); } }
3、建立数据库操作规范,dao(子类和父类有公用方法就用抽象类,不然就用接口)
public interface DeviceMacAddressDao { /** * 把excel中的读入内存的数据并写入数据库中 * @param info */ public void addDeviceMacInfo(MacInfo info); /** * 清空设备mac地址和编号 */ public void clearDeviceMacInfos(); /** * 清空设备mac地址和编号 * @param info 蓝牙信息实体 */ public void deleteDeviceMacInfo(MacInfo info); /** * 获得数据库中所有的蓝牙设备地址和编号 * @return */ public List<MacInfo> getAllMacInfos(); }
4、数据库表操作实现类
public class DeviceMacAddressDaoImpl implements DeviceMacAddressDao { private boolean D = true; private DeviceInfoDBHelper mDbHelper; public DeviceMacAddressDaoImpl(Context context) { mDbHelper = DeviceInfoDBHelper.getInstance(context); } @Override public void addDeviceMacInfo(MacInfo info) { SQLiteDatabase database = null; try { database = mDbHelper.getWritableDatabase(); database.execSQL( "insert into DeviceMacAddress(device_num,device_mac) values(?,?)", new String[] { info.getDeviceNumber(), info.getDeviceMac() }); database.close(); } catch (Exception e) { if (D) { Log.i("蓝牙mac地址", "蓝牙mac地址写入数据库失败!!!"); } } }
...........
5、利用静态工厂获得数据库操作对象类似
/** * 获得对蓝牙地址信息操作实例 * * @param context * @return */ public static synchronized DeviceMacAddressDao getDeviceMacAddressDao(Context context) { if (mDeviceMacAddressDao == null) { mDeviceMacAddressDao = new DeviceMacAddressDaoImpl(context); } return mDeviceMacAddressDao; }
使用数据库操作类进行数据操作时,选择合适的上下文,便于垃圾回收!!!可以使用软引用或软引用。
时间: 2024-10-29 19:13:30