开发者

how to use database in android? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

how to create database in android

I am new to mobile application development.I wish to know how to create and use the database in android. I开发者_StackOverflow社区s there any requirements needed to create the database(like sql)? now i use the eclipse ide.


One of the approaches is to extend SQLiteOpenHelper as below and override onCreate to create the database. Below is a simple example.

public class DBHelper extends SQLiteOpenHelper {

  private static String DB_NAME = "example.db";
  private static int DB_VERSION = 1;

  public DBHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
   db.execSQL("CREATE TABLE props (name TEXT PRIMARY KEY, value TEXT);");
INTEGER);");
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO: Write upgrade db scripts

  }
}

And then you may do a query like

SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables("PROPS");
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c = qb.query(db, new String[]{"value"}, "name = '" + name +"'", null, null, null, null);
if(c.getCount() > 0) {
  c.moveToFirst();
  val = c.getString(c.getColumnIndexOrThrow("value"));
}
closeDbAndCursor(db,c);


Android uses SQLite for its database engine. There are some "helper" classes in the SDK for working with the database.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜