Android provides full support for SQLite databases.Any databases you create will be accessible by name to anyclass in the application, but not outside the application.
The recommended method to create a new SQLite database is to create a subclass ofSQLiteOpenHelper
and override theonCreate()
method, in which youcan execute a SQLite command to create tables in the database.
For example:
public class MyDb extends SQLiteOpenHelper {
public static final String DB_NAME = "student_score.db";//数据库名
public static final String TABLE_NAME = "student_score";//表名
public static final String NAME = "name";//表中第二列 学生姓名
public static final String SCORE = "score";//表中第三列 学生成绩
public MyDb(Context context) {
super(context, DB_NAME, null, 1);// 1 为数据库的版本
}
@Override
public void onCreate(SQLiteDatabase db) {
//创建表
String sql = "create table " + TABLE_NAME + " (_id integer primary key autoincrement," +
NAME + " text," +
SCORE + " text" + ")";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {}
}
You can then get an instance of your
SQLiteOpenHelper
implementation using the constructor you've defined. To write to and read from the database, call
getWritableDatabase()
and
getReadableDatabase()
, respectively. These both return a
SQLiteDatabase
object that represents the database andprovides methods for SQLite operations.
MyDb myDb = new MyDb(context);
SQLiteDatabase readableDatabase = myDb.getReadableDatabase();
Run the application, I found the database file in the databases directory inside application package.
Open the database file is as follows.