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的实例对象,就可以对数据库里的表,进行增删改查的操作了,这些在下一篇里会详细举例说明。