Android数据库操作<一>



     Android开发中,对数据库的操作是非常普遍的。下面通过贴出一些代码,来说明如何创建数据库: 

	public class ZAppSQLOpenHelper extends SQLiteOpenHelper {

	private final static String ZAPP_DB_NAME = "zappDB";
	private final static int VERSION = 1;
	
	public ZAppSQLOpenHelper(Context context) {
		super(context, ZAPP_DB_NAME, null, VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
        //创建info数据表
        StringBuilder sandiBuilder = new StringBuilder();
        sandiBuilder.append("create table if not exists info"); // 表名
        sandiBuilder.append("(id INTEGER PRIMARY KEY AUTOINCREMENT,");
        sandiBuilder.append("one varchar(10),");
        sandiBuilder.append("two varchar(10),");
        sandiBuilder.append("three varchar(10),");
        sandiBuilder.append("time varchar(10),");
        sandiBuilder.append("uuid text)");
        db.execSQL(sandiBuilder.toString());
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("drop table if exists " + ZAPP_DB_NAME);
        onCreate(db);
	}
    }

      可以看到,在Android中创建数据库,只需要继承SQLiteOpenHelper就可以了,其实非常简单,不过对新手来说,
   还是需要一些指引的。
      以上是创建了名为zappDB的数据库,在使用过程中可以调用SQLiteOpenHelper中的getWritableDatabase()方法来
   获得前面创建的数据库,下面代码采用的是单例模式:

	public class ZAppDBUtil {
	
	private static ZAppSQLOpenHelper openHelper = null;
	private static SQLiteDatabase db = null;
	private static ZAppDBUtil dbUtil = null;
	
	public static ZAppDBUtil getInstance(){
		if (null == dbUtil) {
			dbUtil = new ZAppDBUtil();
		}
		if (null == openHelper) {
			openHelper = new ZAppSQLOpenHelper(ZAppApplication.getApplication());
		}
		return dbUtil;
	}
	
	public SQLiteDatabase getSQLiteDatabase(){
		if (null == db) {
			db = openHelper.getWritableDatabase();
		}
		return db;
	}
    }
      取得了SQLiteDatabase的实例对象,就可以对数据库里的表,进行增删改查的操作了,这些在下一篇里会详细举例说明。



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值